Thank you for taking the time to look at this question.... Bear with me....
The other day one of our Web Servers stopped serving up web pages. The Web Server is a physical server running Windows Server 2003 R2 Standard Edition Service Pack 2 with IIS 6. It runs ColdFusion 8.0.1 Standard with Java 1.6.0_24. This server has 3 public-facing websites that really don't get much usage. Pages on all three websites were timing out or returning 500 errors.
When I signed on to the server to see what the problem was, I was expecting to see the JRUN service using a ton of memory. The memory was fine, but, I noticed that the CPU was running at or near 100%. About 50% was being used by JRUN and the other 50% by a runaway backup process, which I killed. But then JRUN quickly ate up the CPU and was using close to 100%.
I looked at the ColdFusion logs and noticed several Java heap space errors occurring.
I looked at the IIS logs and noticed that there were a bunch of requests to an app which allows one of our customers to upload multiple image files for their products using uploadify. The app is written in ColdFusion, and uses jQuery to call a Web Service that handles the upload and resizes the uploaded images using <CFIMAGE>.
After seeing this information in the logs, I figured some part of this app must be the culprit.
I just can't seem to find what exactly caused the Java heap space errors and CPU spike. Any thoughts?
WebService CFC method:
<cffunction
name="uploadFile"
access="remote"
returntype="Struct"
output="false"
returnformat="JSON">
<cfargument name="FileName" type="String" default="" />
<cfargument name="FileData" type="String" default="" />
<cfscript>
var _response = NewAPIResponse();
var _tempFilePath = APPLICATION.TempDir & "\" & ARGUMENTS.FileName;
var _qItem = QueryNew("");
var _product = CreateObject("component", "cfc.Product");
var _result = {};
var _sku = "";
/*
Each file must be named [Part Number].[file extension], so, \
parse the file name to get everything before the file extension
*/
_sku =
Trim(
REQUEST.UDFLib.File.getFileNameWithoutExtension(
ARGUMENTS.FileName
)
);
</cfscript>
<cfif Len(_sku) GT 20>
<cfthrow
message="#ARGUMENTS.FileName#: File Name does not correspond to an existing Part Number." />
</cfif>
<cfset _qItem = _product.readSKU(_sku) />
<cfif NOT _qItem.RECORDCOUNT>
<cfthrow
message="#ARGUMENTS.FileName#: File Name does not correspond to an existing Part Number." />
</cfif>
<cfscript>
FileCopy(ARGUMENTS.FileData, _tempFilePath);
_aMessages =
_product.setId(
_qItem.SKU
).updateThumbnailImages(uploadFilePath = _tempFilePath);
</cfscript>
<cfif ArrayLen(_aMessages)>
<cfthrow
message="#ARGUMENTS.FileName#: #_aMessages[1].getText()#" />
</cfif>
<cfscript>
_result["SKU"] = _product.getSKU();
_result["SMALLIMAGESRC"] = _product.getSmallImageSrc();
_result["LARGEIMAGESRC"] = _product.getLargeImageSrc();
ArrayAppend(_response.data, _result);
</cfscript>
<cfreturn _response />
</cffunction>
Image Resizing Function:
<cffunction name="updateThumbnailImages" returntype="Array" output="false">
<cfargument name="uploadFilePath" type="String" required="true" />
<cfset var _image = {} />
<cfif FileExists(ARGUMENTS.uploadFilePath)>
<cfset _image =
REQUEST.UDFLib.Image.scale(
imagePath = ARGUMENTS.uploadFilePath,
maxHeight = 500,
maxWidth = 700
) />
<cfimage
action="write"
source="#_image#"
overwrite="true"
destination="#getLargeImagePath()#" />
<cfset _image =
REQUEST.UDFLib.Image.scale(
imagePath = ARGUMENTS.uploadFilePath,
maxHeight = 300,
maxWidth = 300
) />
<cfimage
action="write"
source="#_image#"
overwrite="true"
destination="#getMediumImagePath()#" />
<cfset _image =
REQUEST.UDFLib.Image.scale(
imagePath = ARGUMENTS.uploadFilePath,
maxHeight = 50,
maxWidth = 50
) />
<cfimage
action="write"
source="#_image#"
overwrite="true"
destination="#getSmallImagePath()#" />
</cfif>
</cffunction>
Image scaling UDFs:
<cffunction name="getDimensionsToEnlarge" returntype="Struct" output="false">
<cfargument name="imageWidth" type="Numeric" required="true" />
<cfargument name="imageHeight" type="Numeric" required="true" />
<cfargument name="minWidth" type="Numeric" required="true" />
<cfargument name="minHeight" type="Numeric" required="true" />
<cfscript>
var dimensions = {
width = -1,
height = -1
};
if (
ARGUMENTS.minHeight > 0
&& ARGUMENTS.minWidth > 0
&& imageHeight < ARGUMENTS.minHeight
&& imageWidth < ARGUMENTS.minWidth
) {
dimensions.width = ARGUMENTS.minWidth;
dimensions.height = ARGUMENTS.minHeight;
}
return dimensions;
</cfscript>
</cffunction>
<cffunction name="getDimensionsToShrink" returntype="Struct" output="false">
<cfargument name="imageWidth" type="Numeric" required="true" />
<cfargument name="imageHeight" type="Numeric" required="true" />
<cfargument name="maxWidth" type="Numeric" required="true" />
<cfargument name="maxHeight" type="Numeric" required="true" />
<cfscript>
var dimensions = {
width = -1,
height = -1
};
if (
ARGUMENTS.maxHeight > 0
&& ARGUMENTS.maxWidth > 0
&& (
imageHeight > ARGUMENTS.maxHeight
|| imageWidth > ARGUMENTS.maxWidth
)
) {
dimensions.width = ARGUMENTS.maxWidth;
dimensions.height = ARGUMENTS.maxHeight;
}
return dimensions;
</cfscript>
</cffunction>
<cffunction name="getDimensionsToFit" returntype="Struct" output="false">
<cfargument name="imageWidth" type="Numeric" required="true" />
<cfargument name="imageHeight" type="Numeric" required="true" />
<cfargument name="minWidth" type="Numeric" required="true" />
<cfargument name="minHeight" type="Numeric" required="true" />
<cfargument name="maxWidth" type="Numeric" required="true" />
<cfargument name="maxHeight" type="Numeric" required="true" />
<cfscript>
var dimensions = {
width = -1,
height = -1
};
dimensions =
getDimensionsToEnlarge(
imageHeight = ARGUMENTS.imageHeight,
imageWidth = ARGUMENTS.imageWidth,
minWidth = ARGUMENTS.minWidth,
minHeight = ARGUMENTS.minHeight
);
if (dimensions.width < 0 && dimensions.height < 0)
dimensions =
getDimensionsToShrink(
imageHeight = ARGUMENTS.imageHeight,
imageWidth = ARGUMENTS.imageWidth,
maxWidth = ARGUMENTS.maxWidth,
maxHeight = ARGUMENTS.maxHeight
);
return dimensions;
</cfscript>
</cffunction>
<cffunction name="scale" returntype="Any" output="false">
<cfargument name="imagePath" type="String" required="true" />
<cfargument name="action" type="String" default="fit" hint="shrink, enlarge, or fit"/>
<cfargument name="minWidth" type="Numeric" default="-1" />
<cfargument name="minHeight" type="Numeric" default="-1" />
<cfargument name="maxWidth" type="Numeric" default="-1" />
<cfargument name="maxHeight" type="Numeric" default="-1" />
<cfscript>
var scaledDimensions = {
width = -1,
height = -1
};
var scaledImage = ImageNew();
scaledImage = ImageNew(ARGUMENTS.imagePath);
switch (ARGUMENTS.action) {
case "shrink":
scaledDimensions =
getDimensionsToShrink(
imageHeight = scaledImage.getHeight(),
imageWidth = scaledImage.getWidth(),
maxWidth = ARGUMENTS.maxWidth,
maxHeight = ARGUMENTS.maxHeight
);
break;
case "enlarge":
scaledDimensions =
getDimensionsToEnlarge(
imageHeight = scaledImage.getHeight(),
imageWidth = scaledImage.getWidth(),
minWidth = ARGUMENTS.minWidth,
minHeight = ARGUMENTS.minHeight
);
break;
default:
scaledDimensions =
getDimensionsToFit(
imageHeight = scaledImage.getHeight(),
imageWidth = scaledImage.getWidth(),
minWidth = ARGUMENTS.minWidth,
minHeight = ARGUMENTS.minHeight,
maxWidth = ARGUMENTS.maxWidth,
maxHeight = ARGUMENTS.maxHeight
);
break;
}
if (scaledDimensions.width > 0 && scaledDimensions.height > 0) {
// This helps the image quality
ImageSetAntialiasing(scaledImage, "on");
ImageScaleToFit(
scaledImage,
scaledDimensions.width,
scaledDimensions.height
);
}
return scaledImage;
</cfscript>
</cffunction>
Below is the example code I spoke of in the comments section. This improved the reliability for us but under extreme load we found the issue still occured which is why we moved to Java 1.7. However 1.7 had it's own problems as the performance drops dramatically as outlined here. Hope it helps.
<cffunction name="init" access="private" output="false" returntype="void">
<cfset variables.instance = StructNew() />
<!--- create object and set to variables.instance --->
<cfset setProductObject()>
</cffunction>
<cffunction name="setProductObject" access="private" returntype="void" output="false">
<!--- create object once and set it to the variables.instance scope --->
<cfset var product = createObject("component","cfc.Product")>
<cfset variables.instance.product = product/>
<cfset product = javacast('null', '')>
</cffunction>
<cffunction name="getProductObject" access="private" returntype="cfc.Product" output="false">
<!--- instead of creating object each time use the one already in memory and duplicate it --->
<cfset var productObj = duplicate(variables.instance.product)>
<cfreturn productObj />
</cffunction>
<cffunction name="uploadFile" access="remote" returntype="struct" returnformat="JSON" output="false">
<cfargument name="FileName" type="String" default="" />
<cfargument name="FileData" type="String" default="" />
<cfscript>
var _response = NewAPIResponse();
var _tempFilePath = APPLICATION.TempDir & "\" & ARGUMENTS.FileName;
var _qItem = QueryNew("");
var _product = "";
var _result = {};
var _sku = "";
//check init() function has been run if not run it
if NOT structKeyExists(variables,'instance') {
init();
}
_product = getProductObject();
/*
Each file must be named [Part Number].[file extension], so, \
parse the file name to get everything before the file extension
*/
_sku =
Trim(
REQUEST.UDFLib.File.getFileNameWithoutExtension(
ARGUMENTS.FileName
)
);
</cfscript>
<cfif Len(_sku) GT 20>
<cfthrow
message="#ARGUMENTS.FileName#: File Name does not correspond to an existing Part Number." />
</cfif>
<cfset _qItem = _product.readSKU(_sku) />
<cfif NOT _qItem.RECORDCOUNT>
<cfthrow
message="#ARGUMENTS.FileName#: File Name does not correspond to an existing Part Number." />
</cfif>
<cfscript>
FileCopy(ARGUMENTS.FileData, _tempFilePath);
_aMessages =
_product.setId(
_qItem.SKU
).updateThumbnailImages(uploadFilePath = _tempFilePath);
</cfscript>
<cfif ArrayLen(_aMessages)>
<cfthrow
message="#ARGUMENTS.FileName#: #_aMessages[1].getText()#" />
</cfif>
<cfscript>
_result["SKU"] = _product.getSKU();
_result["SMALLIMAGESRC"] = _product.getSmallImageSrc();
_result["LARGEIMAGESRC"] = _product.getLargeImageSrc();
ArrayAppend(_response.data, _result);
</cfscript>
<cfreturn _response />
</cffunction>
Related
This is my Liferay search container code:
MVC:BigInteger leaveTotalCount;
ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
PortletURL iteratorURL = PortletURLFactoryUtil.create(request, themeDisplay.getPortletDisplay().getId(),
themeDisplay.getPlid(), PortletRequest.RENDER_PHASE);
SearchContainer<LeaveDetailsWrapper> searchContainer = null;
searchContainer = new SearchContainer<>(request, null, null, SearchContainer.DEFAULT_CUR_PARAM,
SearchContainer.DEFAULT_DELTA, iteratorURL, null, LmsLeaveDashboardConstant.BLANK_STRING);
List<LeaveDetailsWrapper> leaveDetails;
try {
searchContainer.setDeltaConfigurable(true);
leaveDetails = leaveLocalService.getLeaveDetails(null, null, null, null,
LmsLeaveDashboardUtils.getEmpCode(request), searchContainer.getStart(), searchContainer.getEnd());
log.info(leaveDetails);
leaveTotalCount = leaveLocalService.getLeaveDetailsCount(null, null, null, null,
LmsLeaveDashboardUtils.getEmpCode(request), -1, -1);
searchContainer.setEmptyResultsMessage("No Data Found..!");
searchContainer.setTotal(leaveTotalCount.intValue());
searchContainer.setIteratorURL(iteratorURL);
searchContainer.setResults(leaveDetails);
} catch (Exception e) {
log.error("ERROR:IntrahrmsLmsLeaveDashboardWebPortlet leaveSearchContianer" + e);
}
return searchContainer;
jsp:
<liferay-ui:search-container searchContainer="${leaveInfoContainer}" iteratorURL="${iteratorURL}">
<liferay-ui:search-container-results
results="${leaveInfoContainer.getResults()}" />
<liferay-ui:search-container-row
className="com.intrahrms.lms.service.leavecustom.model.LeaveDetailsWrapper"
modelVar="LeaveDetails">
<liferay-ui:search-container-column-text
value="${LeaveDetails.leaveTypeName} Leave " name="Leave Type" />
<liferay-ui:search-container-column-text name="From Date">
<fmt:formatDate pattern="dd/MM/yyyy"
value="${LeaveDetails.fromDate}" type="date" />
</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="To Date">
<fmt:formatDate pattern="dd/MM/yyyy" value="${LeaveDetails.toDate}"
type="date" />
</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text
value="${LeaveDetails.totalDays}" name="Total Leave Days" />
<liferay-ui:search-container-column-text name="Applied Date">
<fmt:formatDate pattern="dd/MM/yyyy"
value="${LeaveDetails.appliedDate}" type="date" />
</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text
value="${LeaveDetails.leaveStatus} " name="Status" />
<liferay-ui:search-container-column-text
value="${LeaveDetails.projectManagerId}" name="Reporting Manager" />
<liferay-ui:search-container-column-jsp path="/action.jsp"
align="center" />
</liferay-ui:search-container-row>
<liferay-ui:search-iterator markupView="lexicon" />
</liferay-ui:search-container>
The problem is when I'm changing a pagination or change delta, it gives me whole record instead of filter record.
Your search container seems to be doing the right thing as:
leaveDetails = leaveLocalService.getLeaveDetails(null, null, null, null,
LmsLeaveDashboardUtils.getEmpCode(request), searchContainer.getStart(), searchContainer.getEnd());
Think about this: you have just created the instance, what would you expect to be in start and end?
When you created your containers you told it about the parameters it shoudl use, but they are not being set on your JSP, for instance:
<liferay-ui:search-container emptyResultsMessage="there-are-no-file-entries" iteratorURL="${filesRenderUrl}" delta="${files_searchDelta}" total="${files_searchTotal}" curParam="files" deltaParam="files">
bottom line, if you want to control your search container in java methods like that, you will need to act accordingly to set your results:
private static int getStart( int current, int delta ) {
return ( current - 1 ) * delta;
}
private static int getEnd( int first, int delta ) {
return first + delta;
}
I'm trying to create an Excel spreadsheet from scratch using OpenXML and I've got everything working okay (dumping actual values into actual cells), but now I'm trying to apply number formatting to columns and I'm running into a problem. I have styles.xml that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<x:styleSheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<x:numFmts count="12">
<x:numFmt numFmtId="216" formatCode="#,###" />
<x:numFmt numFmtId="217" formatCode="$#,###" />
<x:numFmt numFmtId="218" formatCode="#0.00" />
<x:numFmt numFmtId="219" formatCode="#,###" />
<x:numFmt numFmtId="220" formatCode="#0.0%" />
<x:numFmt numFmtId="221" formatCode="#,###" />
<x:numFmt numFmtId="222" formatCode="#0.0%" />
<x:numFmt numFmtId="223" formatCode="#0.0%" />
<x:numFmt numFmtId="224" formatCode="#0.0%" />
<x:numFmt numFmtId="225" formatCode="#,###" />
<x:numFmt numFmtId="226" formatCode="#,###" />
<x:numFmt numFmtId="227" formatCode="#0.0%" />
</x:numFmts>
<x:cellXfs count="12">
<x:xf numFmtId="216" applyNumberFormat="1" />
<x:xf numFmtId="217" applyNumberFormat="1" />
<x:xf numFmtId="218" applyNumberFormat="1" />
<x:xf numFmtId="219" applyNumberFormat="1" />
<x:xf numFmtId="220" applyNumberFormat="1" />
<x:xf numFmtId="221" applyNumberFormat="1" />
<x:xf numFmtId="222" applyNumberFormat="1" />
<x:xf numFmtId="223" applyNumberFormat="1" />
<x:xf numFmtId="224" applyNumberFormat="1" />
<x:xf numFmtId="225" applyNumberFormat="1" />
<x:xf numFmtId="226" applyNumberFormat="1" />
<x:xf numFmtId="227" applyNumberFormat="1" />
</x:cellXfs>
</x:styleSheet>
But Excel doesn't seem to like it and removes it after "repairing" the file. What am I missing here? The docs are a little spotty on exactly what is needed to keep Excel happy.
I manually assigned the numFmtId starting at what I thought might be a suitably high number. Is that the right way to do it?
Also, I'm aware that the formatCode are duplicated, but I'd assumed Excel wouldn't get tripped up by that, I could consolidate them if necessary.
My column definitions look like this (in sheet.xml):
<x:cols>
<x:col min="1" max="1" width="7" />
<x:col min="2" max="2" width="58" />
<x:col min="3" max="3" width="16" style="0" />
<x:col min="4" max="4" width="6" style="1" />
<x:col min="5" max="5" width="17" style="2" />
<x:col min="6" max="6" width="16" style="3" />
<x:col min="7" max="7" width="18" style="4" />
<x:col min="8" max="8" width="17" style="5" />
<x:col min="9" max="9" width="20" style="6" />
<x:col min="10" max="10" width="21" style="7" />
<x:col min="11" max="11" width="21" style="8" />
<x:col min="12" max="12" width="16" style="9" />
<x:col min="13" max="13" width="16" style="10" />
<x:col min="14" max="14" width="19" style="11" />
</x:cols>
For comparison - here's a snippet from a working styles.xml file created by Excel itself:
<numFmts count="1">
<numFmt numFmtId="164" formatCode="#,##0\p"/> // where does 164 come from?
</numFmts>
<cellXfs count="3">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/> // do you always need a 0 xf entry? It isn't referenced in the sheet.xml file
<xf numFmtId="3" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/> // assuming numFmtId = 3 is a built in format??
<xf numFmtId="164" fontId="0" fillId="0" borderId="0" xfId="0" applyNumberFormat="1"/>
</cellXfs>
Answering my own question, but I came across this post:
http://polymathprogrammer.com/2009/11/09/how-to-create-stylesheet-in-excel-open-xml/
Which suggested that the minimum stylesheet requires quite a few more things than just the numFmts and the cellXfs. So I adapted their code to produce a minimal stylesheet ready for me to insert my cell formats and number formats (which I was doing in a loop):
private Stylesheet CreateStylesheet()
{
Stylesheet ss = new Stylesheet();
Fonts fts = new Fonts();
DocumentFormat.OpenXml.Spreadsheet.Font ft = new DocumentFormat.OpenXml.Spreadsheet.Font()
{
FontName = new FontName()
{
Val = "Calibri"
},
FontSize = new FontSize()
{
Val = 11
}
};
fts.Append(ft);
fts.Count = (uint)fts.ChildElements.Count;
Fills fills = new Fills();
fills.Append(new Fill()
{
PatternFill = new PatternFill()
{
PatternType = PatternValues.None
}
});
fills.Append(new Fill()
{
PatternFill = new PatternFill()
{
PatternType = PatternValues.Gray125
}
});
fills.Count = (uint)fills.ChildElements.Count;
Borders borders = new Borders();
Border border = new Border()
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
};
borders.Append(border);
borders.Count = (uint)borders.ChildElements.Count;
CellStyleFormats csfs = new CellStyleFormats();
CellFormat cf = new CellFormat() {
NumberFormatId = 0,
FontId = 0,
FillId = 0,
BorderId = 0
};
csfs.Append(cf);
csfs.Count = (uint)csfs.ChildElements.Count;
NumberingFormats nfs = new NumberingFormats();
CellFormats cfs = new CellFormats();
cf = new CellFormat()
{
NumberFormatId = 0,
FontId = 0,
FillId = 0,
BorderId = 0,
FormatId = 0
};
cfs.Append(cf);
ss.Append(nfs);
ss.Append(fts);
ss.Append(fills);
ss.Append(borders);
ss.Append(csfs);
ss.Append(cfs);
CellStyles css = new CellStyles();
CellStyle cs = new CellStyle()
{
Name = "Normal",
FormatId = 0,
BuiltinId = 0
};
css.Append(cs);
css.Count = (uint)css.ChildElements.Count;
ss.Append(css);
DifferentialFormats dfs = new DifferentialFormats();
dfs.Count = 0;
ss.Append(dfs);
TableStyles tss = new TableStyles()
{
Count = 0,
DefaultTableStyle = "TableStyleMedium9",
DefaultPivotStyle = "PivotStyleLight16"
};
ss.Append(tss);
return ss;
}
Not positive that there aren't things there that could be dropped, but I don't have the patience to go through it by trial-and-error to see if it can be made any slimmer.
I guess a cell format must have a FontId, FillId, BorderId and FormatId in addition to the NumberFormatId and in order to have those ids, you need to create at least one entry for each of them. This is despite the XML Schema labeling them as "optional".
I have updated a row in Gridview but it is not working.
Here is my code :
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
//Label lbldeleteid = (Label)row.FindControl("Label1");
string bname= GridView1.DataKeys[e.RowIndex].Values["manufacturer"].ToString();
TextBox tbmanu = (TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[1];
var myString = tbmanu.ToString();
SqlCommand cmd = new SqlCommand("manu_upd",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#manufacturer", SqlDbType.NVarChar,100);
cmd.Parameters["#manufacturer"].Value = myString;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
I got the following error :
Unable to cast object of type 'System.Web.UI.LiteralControl' to type
'System.Web.UI.WebControls.TextBox'.
here is my Grid view :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="manufacturer" ForeColor="#333333"
GridLines="None" Width="400px" BorderStyle="Double"
CellSpacing="3" Font-Bold="True" Font-Size="Small" ShowFooter="True"
ShowHeaderWhenEmpty="True" onrowdeleting="GridView1_RowDeleting"
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating"
onrowcancelingedit="GridView1_RowCancelingEdit"
AutoGenerateEditButton="True">
<AlternatingRowStyle BackColor="White"/>
<Columns>
<asp:TemplateField HeaderText="Number" ItemStyle-
HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lbnaumber" runat="server" Text='<%#
Container.DataItemIndex + 1 %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Manufacturer"
SortExpression="manufacturer">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#
Bind("manufacturer") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbmanu" runat="server" Text='<%#
Bind("manufacturer") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<%--<asp:CommandField ShowEditButton="True" />--%>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<EditRowStyle BackColor="#2461BF"/><FooterStyle BackColor="#507CD1"
Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"/>
<PagerStyle BackColor="#2461BF" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" /><SelectedRowStyle BackColor="#D1DDF1"
Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB"/>
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
When I change the index of my text box 1 to 3 it shows me below error :
Specified argument was out of the range of valid values.
Parameter name: index
When i change its index 3 to 2 it gives me below error :
Unable to cast object of type 'System.Web.UI.WebControls.DataControlLinkButton' to type 'System.Web.UI.WebControls.TextBox'.
I have one required field validator in my form but when I enable that validation update in grid view is not working.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox tbmanu1 = (TextBox)row.FindControl("tbmanu");
//or try
//TextBox tbmanu1= (TextBox)row.Cells[0].FindControl("tbmanu");
string myString = Convert.Tostring(tbmanu1.text);
cmd.Parameters["#manufacturer"].Value = myString;
}
Try wrapping your gridview in a asp:UpdatePanel and set the update mode to conditional.
Good Luck
I am actually trying to create a highlighter when dragging i was able to achieve this using the resize state and drawview class. But this is not working when the view is scaled.
When i am trying to drag the mouse sometimes its working and sometimes the selected region is either getting diminished or getting enlarged. I have attached the sample code
<canvas width="1024" height="768" debug="true">
<class name="boxdraw">
<handler name="onmousedown"><![CDATA[
Debug.write("onmousedown");
this.boxview.setAttribute ('x', this.getMouse ('x'));
this.boxview.setAttribute ('y', this.getMouse ('y'));
this.boxview.setAttribute ('width', 0);
this.boxview.setAttribute ('height', 0);
this.boxview.setAttribute ('visible', true);
this.boxview.resizer.apply ();
]]></handler>
<handler name="onmouseup"><![CDATA[
Debug.write("onmouseip");
this.boxview.setAttribute ('visible', false);
this.boxview.resizer.remove ();
]]></handler>
<handler name="oninit" >
this.setAttribute ('clickable', true);
</handler>
<drawview name="boxview" visible="false">
<attribute name="isready" value="false" type="boolean" />
<handler name="oncontext">
this.setAttribute("isready", true);
this.strokeStyle = 0x999999;
this.lineWidth = 2;
</handler>
<handler name="oninit">
this.strokeStyle = 0x999999;
this.lineWidth = 2;
</handler>
<resizestate name="resizer">
<attribute name="minheight" value="${-this.y + 1}"/>
<attribute name="minwidth" value="${-this.x + 1}"/>
<attribute name="maxheight" value="${classroot.height - this.y - 1}"/>
<attribute name="maxwidth" value="${classroot.width - this.x - 1}"/>
<attribute name="xroffset" value="${this.x - this.width + this.getMouse( 'x' )}" />
<attribute name="yroffset" value="${this.y - this.height + this.getMouse( 'y' )}" />
<attribute name="width"
value="${(this.immediateparent.getMouse ( 'x' ) - this.xroffset) > this.maxwidth ?
this.maxwidth :
Math.max((this.immediateparent.getMouse( 'x' )- this.xroffset), this.minwidth)}" />
<attribute name="height"
value="${(this.immediateparent.getMouse ( 'y' ) - this.yroffset) > this.maxheight ?
this.maxheight :
Math.max((this.immediateparent.getMouse( 'y' )- this.yroffset), this.minheight)}" />
<handler name="onwidth">
this._draw ();
</handler>
<handler name="onheight">
this._draw ();
</handler>
<method name="_draw"><![CDATA[
Debug.write("__draw", this.minheight, this.maxheight,this.minwidth,this.maxwidth);
Debug.write("this.xroffset,this.yroffset", this.xroffset,this.yroffset);
Debug.write("this.immediateparent.getMouse ( 'x' )",this.immediateparent.getMouse ( 'x' ),this.immediateparent.getMouse ( 'y' ));
this.clear ();
this.beginPath();
this.lineTo (this.width, 0);
this.lineTo (this.width, this.height);
this.lineTo (0, this.height);
this.lineTo (0, 0);
this.closePath();
this.stroke ();
]]></method>
</resizestate>
</drawview>
</class>
<view name="sample" width="1024" height="600" bgcolor="green" xscale="1.63" yscale="1.53">
<boxdraw name="resizebox"
width="100%" height="100%"
options="ignorelayout"
visible="true"/>
</view>
</canvas>
I'm getting error "The Controls collection cannot be modified because the control contains code blocks."
I want to Export GridView to Excel.
My method is: (it works I've tested it)
private void excel()
{
string dosyaadi;
dosyaadi = "Rapor.xls";
String attachment = "attachment; filename=" + dosyaadi;
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254");
Response.Charset = "windows-1254";
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
gvListele.Parent.Controls.Add(frm);
frm.Controls.Add(gvListele);
frm.RenderControl(htw);
Response.Write(" <meta http-equiv='Content-Type' content='text/html; charset=windows-1254' />" + sw.ToString());
Response.End();
}
And gridview :
<asp:GridView ID="gvListele" runat="server" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3">
<Columns>
<asp:BoundField DataField="talepNo" HeaderText="Talep No" />
<asp:BoundField DataField="urunAdi" HeaderText="İçerik" />
<asp:BoundField DataField="talepEdenBirim" HeaderText="Talep Eden Birim" />
<asp:BoundField DataField="talepKomisyonGelisTarih" HeaderText="Komisyona Geliş Tarihi" />
<asp:BoundField DataField="alimUsulu" HeaderText="Alım Usulü" />
<asp:TemplateField ControlStyle-Width="150" HeaderText="Onay">
<ItemTemplate>
<asp:RadioButton ID="rbOnaylandi" runat="server" Text="Onaylandı" GroupName="rblOnay" />
<asp:RadioButton ID="rbBekletildi" runat="server" Text="Bekletildi" GroupName="rblOnay" />
<asp:RadioButton ID="rbReddedildi" runat="server" Text="Reddedildi" GroupName="rblOnay" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
I think this may be because you're trying to add your GridView to a new HtmlForm, you can export without doing this. Try the following example, and extend as necessary:
protected void excel()
{
String dosyaadi = "Rapor.xls";
Response.Clear();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + dosyaadi + ".xls");
Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
Also ensure you have this override function in your C# codebehind:
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}