AspxPivotGrid and WebCharControl Issues - asp.net

I've got two questions/issues regarding the AspxPivotGrid.
When I use the customization window and add columns in the 'Row Area' and 'Data Area' and update the report. The grid generates properly but the graph doesn't generate. However when you add a field in the 'Column Area', the graph then generates.
It appears that the graph only generates when there are at least a column specified, even though the 'Data Area' headers is exactly the data we need. I have simulated this with the graph demo you have on your site. Is this expected behavior?
Secondly, when I add a DateTime to the 'Row Area' and a String 'Column Area' it's fine. I then swap the columns around, again the pivot is fine. Switch it back again you get the following error:
System.ArgumentException: The type of the "Arguments" argument data member isn't compatible with the date-time scale.
at DevExpress.XtraCharts.SeriesBase.CheckArgumentDataMember(Object dataSource, String dataMember, ScaleType argumentScaleType)
Any suggestions / solutions?

If you have fields in the 'Row Area' and 'Data Area', but not in the 'Column Area', the grid shows the column grand totals. You can show these in the chart by setting the ShowColumnGrandTotals property, e.g.:
ASPxPivotGrid1.OptionsChartDataSource.ShowColumnGrandTotals = True
The default value of not showing grand totals is understandable, since most charts show either:
aggregate values grouped by a row or
column field, but no grand totals, or
only grand total values from rows or
columns.

I was having the same errors:
The type of the "Arguments" argument data member isn't compatible with the numeric scale
The type of the "Arguments" argument data member isn't compatible with the datetime scale
It was happening when user changed the rows by columns or vice-versa in the pivot grid. To workaround this issue, i tried this code, and it works for me:
//Always make the chart visible then perform DataBind() //Sempre deixar o gráfico visivel e depois executar o método DataBind()
try
{
dxGrafico.Visible = true;
dxGrafico.RefreshData();
dxGrafico.DataBind();
}
catch (Exception ex)
{
//Try to fix the error: The type of the "Arguments" argument data member isn't compatible with the <data type> scale //Tentar corrigir o Erro
bool bTeste = false;
bTeste = Ajuste_Grafico_ScaleType(ex);
//If not fix the argument scale type, then show error message label //Se não conseguir corrigir , acrescenta um label com texto da mensagem de erro
if (!bTeste)
{
//Make the chart not visible and Add a label on the Page Control that the owners the chart //Deixar o gráfico invisível e exibir o label com mensagem no objeto PageControl que contém o gráfico
dxGrafico.Visible = false;
try
{
//Error Message (Mensagem de Erro)
ASPxLabel lbl = new ASPxLabel();
lbl.ID = "lblMensagemErroGrafico";
lbl.Text += "\n\n" + "ATENÇÃO: Não Foi possível Processar o Gráfico" + "";
lbl.Text += "\n\n" + "Tente utilizar outro tipo de Gráfico" + "";
lbl.Text += "\n\n" + ex.Message + ""; //lbl.Text += "\n\n" + ex.ToString() + "";
this.pgControl.TabPages[1].Controls.Add(lbl);
}
catch (Exception ex1) { }
}
}
//method Try to fix the error
private bool Ajuste_Grafico_ScaleType(Exception exOrigem)
{
//Try to fix error argument ArgumentScaleType (Tenta ajustar erro)
bool saida = false;
try
{
//Auto
try
{
dxGrafico.SeriesTemplate.ArgumentScaleType = ScaleType.Auto;
dxGrafico.DataBind();
dxGrafico.SeriesTemplate.ValueScaleType = ScaleType.Auto;
dxGrafico.DataBind();
saida = true;
return saida;
}
catch (Exception e) { }
//Numeric
try
{
int n = exOrigem.Message.ToString().IndexOf("Numeric", 0, StringComparison.OrdinalIgnoreCase);
if (n >= 0)
{
dxGrafico.SeriesTemplate.ArgumentScaleType = ScaleType.DateTime;
dxGrafico.DataBind();
dxGrafico.SeriesTemplate.ValueScaleType = ScaleType.DateTime;
dxGrafico.DataBind();
saida = true;
return saida;
}
}
catch (Exception e) { }
//Date Time
try
{
int n = exOrigem.Message.ToString().IndexOf("Date", 0, StringComparison.OrdinalIgnoreCase);
if (n >= 0)
{
dxGrafico.SeriesTemplate.ArgumentScaleType = ScaleType.Numerical;
dxGrafico.DataBind();
dxGrafico.SeriesTemplate.ValueScaleType = ScaleType.Numerical;
dxGrafico.DataBind();
saida = true;
return saida;
}
}
catch (Exception e) { }
}
finally
{
}
return false;
}
It works for the most chart types, but to FullStakedLine happened another error not related here.

Related

How can i get columns added on column?

heres my code below...
TableColumn tc = new TableColumn();
TableColumn[] tc2 = new TableColumn[10];
for(int i=0; i<5, i++){
tc.getColumns().add(tc2[i]);
}
and i try to override commit method for editing cells.
public void commit(Object val) {
// Get the table
TableView<MainTable> t = this.getTableView();
// Get the selected row/column
MainTable selectedRow = t.getItems().get(this.getTableRow().getIndex());
TableColumn<MainTable, ?> selectedColumn = t.getColumns().get(t.getColumns().indexOf(this.getTableColumn()));
// Get current property name
String propertyName = ((PropertyValueFactory) selectedColumn.getCellValueFactory()).getProperty();
// Create a method name conforming to java standards ( setProperty )
propertyName = ("" + propertyName.charAt(0)).toUpperCase() + propertyName.substring(1);
// Try to run the update
try {
// Type specific checks - could be done inside each setProperty() method
if(val instanceof Double) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, double.class);
method.invoke(selectedRow, (double) val);
}
if(val instanceof String) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, String.class);
method.invoke(selectedRow, (String) val);
}
if(val instanceof Integer) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, int.class);
method.invoke(selectedRow, (int) val);
}
} catch (Exception e) {
e.printStackTrace();
}
// CommitEdit for good luck
commitEdit((String) val);
}
and i got ArrayIndexOutofBoundsException on console view.
so my question is
how can i select getcolumns added other column???
TableColumn<MainTable, ?> selectedColumn = t.getColumns().get(t.getColumns().indexOf(this.getTableColumn()));
i think this code has to be changed...
anyone got ideas??
Nested columns are not part of the TableView.columns list.
If you need the corresponding TableView column, just go up through the hierarchy until you reach a column without a parentColumn:
TableColumn<MainTable, ?> selectedColumn = this.getTableColumn();
TableColumn<MainTable, ?> c = selectedColumn;
while ((c = selectedColumn.getParentColumn()) != null) {
selectedColumn = c;
}
If you just need the column itself, simply use this.getTableColumn(), instead of finding the index of the column in the columns list and then accessing that index in the same list. (I guess the latter is what you need.)
Furthermore, if PropertyValueFactory returns properties of the item class, you could use this property to set the value instead of using reflection:
ObservableValue obs = selectedColumn.getCellObservableValue(this.getIndex());
if (obs instanceof WritableValue) {
((WritableValue) obs).setValue(val);
} else {
// reflecitive approach
}
Furthermore you shouldn't add null as a nested column, but you're doing it here:
TableColumn[] tc2 = new TableColumn[10];
for(int i=0; i<5, i++){
tc.getColumns().add(tc2[i]);
}

Show static non-clickable heading in AutoCompleteExtender list

I have an AutoCompleteExtender from the Ajax Control Toolkit. I need to have a heading in the dropdown list that shows how many items found, but it should not be selectable as an item.
I have tried this using jQuery, but even when I just add as a div, it is still selected as an item into the text box when I click on it:
function clientPopulated(sender, e) {
var completionList = $find("AutoCompleteEx").get_completionList();
var completionListNodes = completionList.childNodes;
for (i = 0; i < completionListNodes.length; i++) {
completionListNodes[i].title = completionListNodes[i]._value.split(':')[2];
}
var resultsHeader;
if(completionListNodes.length==1000)
resultsHeader = 'Max count of 1000 reached.<br/>Please refine your search.';
else if(completionListNodes.length>0)
resultsHeader = completionListNodes.length + ' hits.';
else
resultsHeader = msg_NoObjectsFound ;
jQuery(completionListNodes[0]).before('<div>' + resultsHeader + '</div>');
}
Add OnClientItemSelected and OnClientShowing events handlers and try script below:
function itemSelected(sender, args) {
if (args.get_value() == null) {
sender._element.value = "";
}
}
function clientShowing() {
var extender = $find("AutoCompleteEx");
var optionsCount = extender.get_completionSetCount();
var message = "";
if (optionsCount == 1000) {
message = 'Max count of 1000 reached.<br/>Please refine your search.';
}
else if (optionsCount > 0) {
message = optionsCount + " hits."
}
else {
message = "oops."
}
jQuery(extender.get_completionList()).prepend("<li style='background-color:#ccc !important;'>" + message + "</li>");
}
Added:
you even can do this without OnClientItemSelected handler:
function clientShowing() {
var extender = $find("AutoCompleteEx");
var oldSetText = extender._setText;
extender._setText = function (item) {
if (item.rel == "header") {
extender._element.value = "";
return;
}
oldSetText.call(extender, item);
};
var optionsCount = extender.get_completionSetCount();
var message = "";
if (optionsCount == 1000) {
message = 'Max count of 1000 reached.<br/>Please refine your search.';
}
else if (optionsCount > 0) {
message = optionsCount + " hits."
}
else {
message = "oops."
}
jQuery(extender.get_completionList()).prepend("<li rel='header' style='background-color:#ccc !important;'>" + message + "</li>");
}
We can give a better answer if you post the output html of your autocomplete control. Anyway if its a dropdown control;
jQuery(completionListNodes[0]).before('
<option value="-99" disabled="disabled">your message here</option>'
);
The answer by Yuriy helped me in solving it so I give him credit although his sollution needed some changes to work.
First of all, the clientShowing event (mapped by setting OnClientShowing = "clientShowing" in the AutoExtender control) is executed on initialization. Here we override the _setText method to make sure nothing happens when clicking on the header element. I have used the overriding idea from Yuriy's answer that really did the trick for me. I only changed to check on css class instead of a ref attribute value.
function clientShowing(sender, e) {
var extender = sender;
var oldSetText = extender._setText;
extender._setText = function (item) {
if (jQuery(item).hasClass('listHeader')) {
// Do nothing. The original version sets the item text to the search
// textbox here, but I just want to keep the current search text.
return;
}
// Call the original version of the _setText method
oldSetText.call(extender, item);
};
}
So then we need to add the header element to the top of the list. This has to be done in the clientPopulated event (mapped by setting OnClientPopulated = "clientPopulated" in the AutoExtender control). This event is executed each time the search results have been finished populated, so here we have the correct search count available.
function clientPopulated(sender, e) {
var extender = sender;
var completionList = extender.get_completionList();
var completionListCount = completionList.childNodes.length;
var maxCount = extender.get_completionSetCount();
var resultsHeader;
if(completionListCount == maxCount)
resultsHeader = 'Max count of ' + maxCount + ' reached.<br/>'
+ 'Please refine your search.';
else if(completionListCount > 0)
resultsHeader = completionListCount + ' hits.';
else
resultsHeader = 'No objects found';
jQuery(completionList).prepend(
'<li class="listHeader">' + resultsHeader + '</li>');
}
I have also created a new css class to display this properly. I have used !important to make sure this overrides the mousover style added from the AutoExtender control.
.listHeader
{
background-color : #fafffa !important;
color : #061069 !important;
cursor : default !important;
}

How to get the DataSourceId?

private SqlDataSource GetDataSource()
{
object o = Session["selectedDataSource"];
DataSourceType dsType = DataSourceType.Gtable;
if (o != null)
dsType = (DataSourceType)o;
switch (dsType)
{
case DataSourceType.tableT:
return DataSourceTID;
case DataSourceType.tableR:
return DataSourceRID;
case DataSourceType.tableC:
return DataSourceCID;
default:
return DataSourceCID;
}
}
For getting the datasourceid I wrote that code.But that gives the error as "Specified cast is not valid".This error is arise at dsType=(DataSourceType)o line.
Please give me any suggextions.
Use enum parse method
http://msdn.microsoft.com/en-us/library/essfb559.aspx
DataSourceType dsType = (DataSourceType) Enum.Parse(typeof(DataSourceType), o);

Html strip in asp.net

I have used a ckeditor in which user can submit data to the database in styles but when the data is populated in the datagrid then also it comes with same styles in IE
but I want it to be in plain text when get populated.
the function for populating the data is as follows:
protected void LoadQA(int intQuestionId)
{
string strSelectQuery = "SELECT TITLE, DESCRIPTION, ANSWER, FK_OWNER_ID, CREATED_ON FROM M_QA WHERE PK_ID = "
+ intQuestionId + " AND IS_ACTIVE = 1";
OleDbConnection connectionSelectQuestion = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
OleDbCommand commandSelectQuestion = new OleDbCommand(strSelectQuery, connectionSelectQuestion);
OleDbDataReader readerSelectQuestion;
try
{
connectionSelectQuestion.Open();
readerSelectQuestion = commandSelectQuestion.ExecuteReader();
if (readerSelectQuestion.Read())
{
lblHeader.Text = "View Q&A";
txtTitle.Text = readerSelectQuestion["TITLE"].ToString();
if (readerSelectQuestion["TITLE"].ToString().Length > 50)
{
ViewState["QA_Title"] = readerSelectQuestion["TITLE"].ToString().Substring(0, 50) + "...";
}
else
{
ViewState["QA_Title"] = readerSelectQuestion["TITLE"].ToString();
}
txtDescription.Text = readerSelectQuestion["DESCRIPTION"].ToString();
hlnkQuestionBy.Text = clsCommons.SayUserName(readerSelectQuestion["FK_OWNER_ID"].ToString());
hlnkQuestionBy.NavigateUrl = "AddMember.aspx?id=" + readerSelectQuestion["FK_OWNER_ID"].ToString();
lblAskedOn.Text = readerSelectQuestion["CREATED_ON"].ToString();
if (this.Session["UserId"].ToString() != "1")
{
btnUpdate.Visible = false;
txtEditorAnswer.Visible = false;
divQaDescription.Visible = true;
divQaDescription.InnerHtml = Server.HtmlDecode(readerSelectQuestion["ANSWER"].ToString());
}
else
{
txtEditorAnswer.Text = readerSelectQuestion["ANSWER"].ToString();
}
}
else
{
lblError.Text = "ERROR WHILE READING QA DATA!";
}
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
lblError.Text = ex.Message;
}
finally
{
if (connectionSelectQuestion != null)
{
connectionSelectQuestion.Close();
}
}
}
What changes I need to make to get the plain text in the datagrid.
Thanks for ur help..
here is some sql code that can strip the tags for you.
declare #string varchar(max), --string to remove html from
#a varchar(max), --holds left part of string after removal
#b varchar(max) --holds right part of string after removal
set #string='<htlml><head><title></title></head><body>This is the body. <p>This is a paragraph.</p></body></html>'
declare #i bit, --determines if there are any more tags in the string
#start int, --position of the first < character
#end int --position of the first > character
set #i='false' --set default value
--set the positions of the first tag
select #start=CHARINDEX('<',#string),
#end=charindex('>',#string)
--only do the loop if there is a tag
if (#start>0 and #end>0) set #i='true'
while (#i='true')
begin
set #a='' --reset
set #b='' --reset
set #a=LEFT(#string,#start-1)
set #b=RIGHT(#string,len(#string)-#end)
--select #a, #b
set #string=#a+#b
select #start=CHARINDEX('<',#string),
#end=charindex('>',#string)
if (#start>0 and #end>0) set #i='true' else set #i='false'
end
select #string
keep in mind, however, that this code does not take into consideration if the text contains a < or >.

RadGrid Custom Filter

I'm trying to add a custom filter to my RadGrid. I have a column, vendNum, which I want to allow users to filter on multiple vendNums with a comma-separated list. Basically, I want the same functionality as an "in" statement in SQL (where vendNum in (X,Y,Z)).
I followed the tutorial on this site and came up with the following code to place in my RadGrid1_ItemCommand event.
protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.FilterCommandName)
{
Pair filterPair = (Pair)e.CommandArgument;
switch (filterPair.Second.ToString())
{
case "vendNum":
TextBox tbPattern = (e.Item as GridFilteringItem)["vendNum"].Controls[0] as TextBox;
if (tbPattern.Text.Contains(","))
{
string[] values = tbPattern.Text.Split(',');
if (values.Length >= 2)
{
e.Canceled = true;
StringBuilder newFilter = new StringBuilder();
for (int i = 0; i < values.Length; i++)
{
if (i == values.Length - 1)
newFilter.Append("[vendNum] = " + values[i]);
else
newFilter.Append("[vendNum] = " + values[i] + " OR ");
}
if (RadGrid1.MasterTableView.FilterExpression == "")
RadGrid1.MasterTableView.FilterExpression = newFilter.ToString();
else
RadGrid1.MasterTableView.FilterExpression = "((" + RadGrid1.MasterTableView.FilterExpression + ") AND (" + newFilter.ToString() + "))";
RadGrid1.Rebind();
}
}
break;
default:
break;
}
}
}
Doing this, though, keeps giving me an error "Expression Expected" when I try to filter with a comma separated list. I'm still able to filter a single vendNum. My FilterExpression does come out as expected. The code is failing on the RadGrid1.Rebind() statement. Has anyone dealt with this before? Any help is greatly appreciated.
Thanks,
Aaron
Forgot to Edit This
I solved this problem weeks ago...I had to set the "EnableLinqExpressions" property to false under the RadGrid.
I saw this as a fix for this question somewhere.
Try adding:
RadGrid1.EnableLinqExpressions = false;

Resources