Showing posts with label Devexpress. Show all posts
Showing posts with label Devexpress. Show all posts

Wednesday, 9 October 2013

How to resolve "The+input+is+not+a+valid+Base-64+string+as+it+contains+a+non-base+64+character%2c+more+than+two+padding+characters%2c+or+a+non-white+space+character+among+the+padding+characters"

I am getting the following exception after performing AspxCallbackPanel  Callaback. I have one "ASPxPanel" control inside the AspxCallbackPanel  control. I am adding devexpress "WebChartControl" control to the "ASPxPanel" control during the AspxCallbackPanel  callback at runtime.

Issue:
===

?DXCallbackErrorMessage=The+input+is+not+a+valid+Base-64+string+as+it+contains+a+non-base+64+character%2c+more+than+two+padding+characters%2c+or+a+non-white+space+character+among+the+padding+characters.

Code:
====

 protected void cbpTestComponents_Callback(object sender, CallbackEventArgsBase e)
{
         for(int i=0;i<3;i++)
        {
                   WebChartControl  dynamicCharControl = new WebChartControl();
                   dynamicCharControl.ShowLoadingPanel = false;
                  dynamicCharControl.ID = "grphDynmicChart_MyDashboard";
                  dynamicCharControl.ClientInstanceName = dynamicCharControl.ID;
                  pnlTestComponents.Controls.Add(dynamicCharControl);
                  dynamicCharControl.DataSource = searchresultDt;
                  dynamicCharControl.DataBind();
                 dynamicCharControl.EnableCallBacks = true;
                 dynamicCharControl.Width = 620;
                 dynamicCharControl.Height = 220;
      }

}
I am getting above exception during the controls add at  cbpTestComponents_Callback

Solution:
======
Here i found the problem is dynamically created control ID(  dynamicCharControl.ID = "grphDynmicChart_MyDashboard";) is same for all the dynamically created controls. So i have to give unique name to each dynamically created controls at runtime.

issue Fix Code:
==========

 protected void cbpTestComponents_Callback(object sender, CallbackEventArgsBase e)
{
         for(int i=0;i<3;i++)
        {
                   WebChartControl  dynamicCharControl = new WebChartControl();
                   dynamicCharControl.ShowLoadingPanel = false;
                  dynamicCharControl.ID = "grphDynmicChart_MyDashboard_" +i.ToString();
                  dynamicCharControl.ClientInstanceName = dynamicCharControl.ID;
                  pnlTestComponents.Controls.Add(dynamicCharControl);
                  dynamicCharControl.DataSource = searchresultDt;
                  dynamicCharControl.DataBind();
                 dynamicCharControl.EnableCallBacks = true;
                 dynamicCharControl.Width = 620;
                 dynamicCharControl.Height = 220;
      }

}




Wednesday, 2 October 2013

Create Callback control like devexpress aspxCallback using ICallbackEventHandler

Today I am very very happy because i learned  new concepts like events/ Custom event argument/delegate / ICallbackEventHandler/ How to set default prefix to the user control ex: instead of cc:Control i will use my own prefix like "asp" asp:Control/  How to create nested properties to the control.

 Now i will explain how to create "Callback" Control using "ICallbackEventHandler" and Custom Control .

1. Need to Create library project Name as "CallbackCtrlLib" and Create one class called "Callback" and inherit "Callback" from the "WebControl, System.Web.UI.ICallbackEventHandler" to achieve callback functionality.

2. How to set default prefix to the custom/user/web user control
Ans: In general if we are not specify any prefix to the custom/user/web user control it will take "cc" as default prefix whenever your drag and drop the particular user control in the page it will shows like this

 <cc:Callback ID="Callback1" runat="server" />

But i want to change the default prefix "cc" to my own prefix like "asp"  or any thing you want. To achieve this one we need to include the following line before the name space of the custom/web user control.

    [assemblyTagPrefix("CallbackCtrlLib", "asp")]


Here first argument of  "TagPrefix"  will expect name space of the control and second argument will be prefix name of the user control. Here "CallbackCtrlLib" is the name space of the Callback Control and "asp" is the my control prefix name it can be anything.


3. How to Create Nested properties to the Control/describing asp.net control properties declaratively
Ans: I want to create nested properties to the user control to create different clientside events
To achieve above thing we need to do the following things:

A) We need to use  [ParseChildren(true)] and   [PersistChildren(true)] in the top of the class to achieve nested properties

B) First we need to create "ClientSideEvents " as class and we need to use that "ClientSideEvents " as property return datatype.

Ex:
==
 public class ClientSideEvents
    {
        private string _endCallback;
        private string _callbackError;
        private string _callbackcomplete;

        public string CallbackError
        {
            get { return _callbackError; }
            set { _callbackError = value; }
        }

        public string EndCallback
        {
            get { return _endCallback; }
            set { _endCallback = value; }
        }

        public string CallbackComplete
        {
            get { return _callbackcomplete; }
            set { _callbackcomplete = value; }
        }
    }

"ClientSideEvents " will contains 3 properties  1) CallbackError 2) EndCallback 3) CallbackComplete

C) We need to create "ClientSideEvents " property . And nee to use [PersistenceMode(PersistenceMode.InnerProperty)] and [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] as the top of the property.

Ex:
==
      private ClientSideEvents _clientSideEvents;

      [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public ClientSideEvents ClientSideEvents
        {
            get
            {
                if (_clientSideEvents == null)
                    _clientSideEvents = new ClientSideEvents();
                return _clientSideEvents;
            }
        }

4. Now we need to create delegates and events for the User/Web control to handle custom callback
   
A) Need to create custom event argument class to pass custom event args to the event handler. Here i am passing "Parameter"" and "Result" are the custom arguments to the "CustomCallback" event.

   ex:
    ==
    public class CallbackEventArgs:EventArgs
    {
        public String Parameter {get;set;}
        public String Result {get;set;}
    }

B) Need to write a function which is reference to an event called "CustomCallback".  if "CustomCallback" is not null means user provided/implemented event logic to the user control in the page so we need invoke/execute the event otherwise no need to execute/invoke event.

ex:
==
  public delegate void EventHandler(Object obj, CallbackEventArgs e);
        public event EventHandler CustomCallback;
        private string _clientInstanceName;
        protected void OnCustomCallback()
        {
            if (CustomCallback != null)
            {
                CustomCallback(this, new CallbackEventArgs());
            }
        }

5) Need to create one "div" element which will play key role in the "Callback" control. We need to override "Render" event  in that we need to create "div" element.

Ex:
==
 [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write("<div id=\"" +  (ClientInstanceName !=null ? ClientInstanceName : this.ID) + "\"></div>");
          
        }

Here "ClientInstanceName " is the property of the user control. User can perform call back using ClientinstanceName or User Control ID.

6) Now we need to implement "RaiseCallbackEvent" of  ICallbackEventHandler. Here we will customize  "RaiseCallbackEvent" with our custom events.  Here i will invoke/Execute OnCustomCallback" of the user control.  As i mentioned in the above i will pass custom event arguments to the  "CustomCallback" event. Here i will assign "CallbackEventArgs " Parameter value with  "eventArgument". I will use it in the "OnCustomCallback" event of the user control and from there i will return  "CallbackEventArgs " "Result" value.
     

Ex:
==
    CallbackEventArgs objCallbackEvtargs = new CallbackEventArgs();
        public void RaiseCallbackEvent(String eventArgument)
        {

            try
            {
                if (CustomCallback != null)
                {
                    objCallbackEvtargs.Parameter = eventArgument;
                    CustomCallback(this, objCallbackEvtargs);
                }
            }
            catch { throw; }
          
        }

7)   Now we need to implement "GetCallbackResult()" of  ICallbackEventHandler. I will return the "CustomCallback" event argument "Result" value to the user.

Ex:
==
   public String GetCallbackResult()
        {

            return objCallbackEvtargs.Result;
        }

8) Now final and very tricky logic. Here we need to get callback reference of the control and need to add it to the page during override of "OnLoad" event. And also we need to implement some client side methods like "element.PerformCallback()". Implementation of clientside events is done with the help of "jquery" and "Ajax Javascript Framework" like "Sys.Application" namespace. This "Sys.Application" will work only when "ScriptManager" presents in the Masterpage/Page otherwise it will throw "Sys.Application" undefined javascript error.


Ex:
==

 protected override void OnLoad(EventArgs e)
        {

            if (CustomCallback != null)
            {
                String cbReference = Page.ClientScript.GetCallbackEventReference(this, "parm", (CustomCallback != null ? (ClientSideEvents.CallbackComplete != null ? ClientSideEvents.CallbackComplete : "ReceiveServerData") : "null"), "this", this.ClientSideEvents.CallbackError, false);
                Page.ClientScript.RegisterStartupScript(this.GetType(),
                    "AttachCallbackEvent", "function AttachCallbackEvent(src,callbackId,callbackScript){Sys.Application.add_init(function () { myObj = {PerformCallback: function (parm) { eval(callbackScript); }};  $.extend($get(src), myObj);});}", true);

                Page.ClientScript.RegisterStartupScript(this.GetType(), this.ID + "_" + "AttachCallbackEvent", "AttachCallbackEvent(\"" + (ClientInstanceName != null ? ClientInstanceName : this.ID) + "\",\"" + this.UniqueID + "\",\"" + cbReference + "\");", true);
            }

            base.OnLoad(e);
        }

Here i have one common javascript function "AttachCallbackEvent" which is common to attach clientside callback events to elements. "AttachCallbackEvent"  will expect clientinstancename or ID of the user control  as "src" and User Control Callback Reference script as "callbackScript" and  User Control unique id as "callbackId". "callbackId" is not used.

During the  "User Control Callback Reference" generation i am checking that if any clientside events. If any thing is defined then i am taking that events else i am using default clientside events.

Here "PerformCallback" clientside function will be attached based on the "Src" parameter. During the "PerformCallback" i am executing "User Control Callback Reference" script.

Here  i am checking if  " if (CustomCallback != null)" then only i am attaching callback events otherwise i am not doing because i am doing all the operation based on the "OnCustomCallback" event.


Complete Example with Working Code : Download




Finally i am very very thanks to

Robert Wray  

Google

Stackoverflow



References:
========

Callback Example:
=================

http://msdn.microsoft.com/en-us/library/ms178210(v=vs.100).aspx

How to create Custom Control Properties Declaratively like dropdownlist items:
=============================================================
http://www.robertwray.co.uk/blog/2008/02/describing-aspnet-control-properties-declaratively.html

Set Default Prefix of custom Control
====================================
http://msdn.microsoft.com/en-us/library/system.web.ui.tagprefixattribute.tagprefixattribute.aspx






    











Wednesday, 4 September 2013

How to display alert message from javascript inside the ASPXCallbackPanel

protected void OnCallback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
         ASPxCallbackPanel callbackPanel = (ASPxCallbackPanel)source;       
          callbackPanel.Controls.Add(new LiteralControl("My New Content"));        
         WebControl script = new WebControl(HtmlTextWriterTag.Script);        
      callbackPanel.Controls.Add(script);        
      script.Attributes["id"] = "dxss_123456";        
    script.Attributes["type"] = "text/javascript";        
     script.Controls.Add(new LiteralControl("var str = 'test'; alert(str);"));    
}

How to Display context menu in AspxGridView Column Headers


Default.aspx:
=============

<dx:ASPxGridView ID="grvContexMenuExample" runat="server" AutoGenerateColumns="false" KeyFieldName="ID" EnableViewState="true" ClientInstanceName="grdtest" Width="100%" Settings-GridLines="None" OnHtmlRowPrepared="grvContexMenuExample_HtmlRowPrepared">
    <ClientSideEvents ContextMenu="function(s,e) {
             if(e.objectType == 'header')
              {
                 headerContextMenu.ShowAtPos(e.htmlEvent.clientX, e.htmlEvent.clientY);
}
                                                         else if(e.objectType == 'row')
                                                         {
                                                             headerContextMenu.ShowAtPos(e.htmlEvent.clientX, e.htmlEvent.clientY);
                                                         }
                                                    }" />
    <Columns>

    <%--Your columns goes here--%>
        <columns>
</dx:ASPxGridView>

<!--Start New  Context Menu !-->
<dx:ASPxPopupMenu ID="mnContextMenu" runat="server" ClientInstanceName="headerContextMenu"
    EnableAnimation="false" PopupHorizontalAlign="OutsideRight" PopupVerticalAlign="TopSides"
    PopupAction="RightMouseClick">
    <Items>
        <dx:MenuItem Text="New Context Menu1">
        </dx:MenuItem>
    </Items>
    <ClientSideEvents ItemClick="ContextMenuItemClick" />
</dx:ASPxPopupMenu>
<!--End New   Context Menu !-->






Default.aspx.cs:
================

  protected void grvContexMenuExample_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
        {


            if (e.RowType == GridViewRowType.Data)

                if (e.RowType == GridViewRowType.Header)
                {

                    e.Row.Attributes.Remove("oncontextmenu");
                }


        }

How to show aspxpopup control on button click instead of enter key press

Steps:
==== 
1. I have two textboxes  and one button and one aspxpopupcontrol in a aspxwebpage

2. I attached  Keypress event for two textboxes and i have attached button OnClientClick event from C#     code behind to show aspxpopupcontrol.
3. Here problem is when ever i enter some data in any one of the text and press enter it is executing           textbox keypress event as well as it showing aspxpopupcontrol. it is very annoying to the user.
4. I resolved this issue by using the following devexpress client side method  in textbox keypress event.
                       ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);

 Example:
========

  <dx:ASPxTextBox runat="server" ID="txtSearch" ClientInstanceName="txtSearch" NullText="Search by Text"  Style="border-radius: 4px 4px 4px 4px;">
  <ClientSideEvents  KeyPress="function(s,e){ 
                                                                var keypressed=ASPxClientUtils.GetKeyCode(e.htmlEvent);
                                                                if(keypressed ==13)
                                                                  { 
                                                                        //Your client side functionality goes here
                                                                        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
                                                                  }}" />
  </dx:ASPxTextBox> 

<dx:ASPxTextBox runat="server" ID="txtTagSearch" ClientInstanceName="txtTagSearch" NullText="Search by Tag"  Style="border-radius: 4px 4px 4px 4px;">
  <ClientSideEvents  KeyPress="function(s,e){ 
                                                                var keypressed=ASPxClientUtils.GetKeyCode(e.htmlEvent);
                                                                if(keypressed ==13)
                                                                  { 
                                                                        //Your client side functionality goes here
                                                                        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
                                                                  }}" />
  </dx:ASPxTextBox> 


 <asp:ImageButton ID="btnShowCustomViewBuilder" CausesValidation="true" runat="server" ImageUrl="~/Styles/Images/FilterIcon.png"
                                                         OnClientClick=" popup.Show();  return false"    />

<dx:ASPxPopupControl ID="AspxPopupControl1" runat="server" Modal="True" AutoUpdatePosition="true" HeaderStyle-Font-Bold="true"
    PopupHorizontalAlign="WindowCenter" PopupVerticalAlign="WindowCenter" AllowDragging="true" AccessibilityCompliant="false" 
    ShowLoadingPanel="false" HeaderText="Example Popup" ClientInstanceName="popup"  PopupAction="LeftMouseClick" 
    Width="520px">
    <ContentCollection>
        <dx:PopupControlContentControl ID="PopupControlContentControl3" runat="server" SupportsDisabledAttribute="True">

<table>
<tr>
<td> //Your content goes here  </td>
</tr>
</table>

  </dx:PopupControlContentControl>
    </ContentCollection>
</dx:ASPxPopupControl>


Reference to resolve above issue

How filter Date Column data in Devexpress XPO XPDataView

public string GetCreatedDate(string period, string column, string customFilterFrom = null, string                CustomFilterTo = null)
        {

            string date = string.Empty; string filterexp = string.Empty;
            DateTime dt = DateTime.Today;
            switch (period.ToUpper())
            {

                case "CUSTOM":
                    date = new BetweenOperator(column, Convert.ToDateTime(customFilterFrom.Replace("/", "-                                  ")),       Convert.ToDateTime(CustomFilterTo.Replace("/", "-"))).ToString();

                    break;
                case "TODAY":
                    date = new BetweenOperator(column, dt, dt.AddDays(1)).ToString(); //string.Format("[{1}]                                    = #{0}#", dt, column);//.ToString("MM/dd/yyyy")
                    break;
                case "LASTDAY":
                     date = new BetweenOperator(column,dt.AddDays(-1),dt).ToString();
                    break;
                case "THISYEAR":
                    date = new BetweenOperator(column, new DateTime(DateTime.Now.Year, 4, 1),                                                      dt.AddDays(1)).ToString();
                    break;

                case "THISMONTH":
                    date = new BetweenOperator(column, new DateTime(DateTime.Now.Year,                                                             DateTime.Now.Month, 1), dt.AddDays(1)).ToString();
                    break;
                case "LASTMONTH":
                    date = new BetweenOperator(column, new DateTime(DateTime.Now.Year,                                                            DateTime.Now.Month, 1).AddMonths(-1), new DateTime(DateTime.Today.Year,                                          DateTime.Today.Month, 1).AddDays(-1)).ToString();
             
                    break;
                case "THISWEEK":
                    int days = (DateTime.Now.DayOfWeek - DayOfWeek.Sunday) - 1;
                    DateTime thisweek = DateTime.Now.AddDays(-(days));
                    date = new BetweenOperator(column, thisweek, thisweek.AddDays(days)).ToString();
                    break;
                case "LASTWEEK":
                    int diff = (DateTime.Now.DayOfWeek - DayOfWeek.Sunday) + 6;
                    DateTime mondayOfLastWeek = DateTime.Now.AddDays(-diff);
                    date = new BetweenOperator(column, mondayOfLastWeek,                                                                                 mondayOfLastWeek.AddDays(diff -6)).ToString();
                     break;
                default:
                    date = string.Format("[{0}] = '{1}'", column, period);
                    break;

            }
            return date;
        }



Refer my original post in devexpress : Unable to filter date values in xpo DataSource

Monday, 2 September 2013

How to inspect HTML elements in the browser

Internet explorer

Check whether the Developer Toolbar is installed on your machine. If you are using IE8+, this tool is already integrated in your browser. Otherwise, you need to install it manually. If the Developer Tool is installed, perform the following steps:
1. Execute Developer Toolbar by pressing the F12 key on your keyboard. Alternatively, click the Tools -> F12 Developer tools menu as shown below.
2. The Developer Tools window will be displayed;
3. Click the Select element button;
4. Click an element on the page;
5. A corresponding HTML element will be selected in the HTML window;
6. Now we know that the CSS rule with the “testRule” name is applied to the element;
7. Find this rule in the Style window as shown below:
Firefox
The Firebug add-on is used for this purpose. Check whether this tool is installed on your machine and perform the following steps:
1. Execute Firebug by pressing the F12 key on your keyboard. Alternatively, click the Tools -> Web Developer -> Firebug -> Open Firebug menu as shown below.
2. The Firebug window will be displayed;
3. Click the button that is shown below to inspect a corresponding element;
4. Click the element on the page;
5. A corresponding HTML element will be selected in the HTML window;
6. Determine the rule name as shown above;
7. Find this rule in the Style window as shown below:
Chrome
Use Developer Tools to accomplish this task.
1. Execute Developer Tools by pressing the F12 key on your keyboard. Alternatively, click the Menu -> Tools -> Developer tools menu as shown below.

2. The Developer Tools window will be displayed;
3. Click the button that is shown below to inspect a corresponding element;
4. Click the element on the page;
5. A corresponding HTML element will be selected in the HTML window;
6. Determine the rule name as shown above;
7. Find this rule in the Style window as shown below:
Opera
Use the Opera Dragonfly tool.
1. Execute the Opera Dragonfly tool by pressing the Ctrl+Shift+I key combination on your keyboard. Alternatively, click the Menu -> Page -> Developer Tools -> Opera Dragonfly menu as shown below.
2. The Opera Dragonfly tool window will be displayed;
3. Check whether the following buttons are pressed as shown below:
4. Click the element on the page;
5. A corresponding HTML element will be selected in the HTML window;
6. Determine the rule name as shown above;
7. Find this rule in the Style window as shown below:
Safari

1. Click the Safari settings -> Preferences... menu as shown below.
2. In the Settings window click the Advanced tab and enable the Show Develop menu in menu bar option as shown below.
3. Close the Settings window and click the Menu for current page -> Develop -> Show Web Inspector menu.
The remaining steps are the same as for Google Chrome.


How to Send Email from Python

Please find the below sample code to send email from Python. import os import smtplib from email.mime.multipart import MIMEMultipart...