Private properties in Userobject?
Hello all,
We are in the middle of studying a Sharepoint environment. We want to use the user profile page, and later on MySite, for a companies adress book. In the present company adress book users can read their pincode for the printer (Uniflow print system). The
present address book reads data from an external system. What we want to achieve is to put the print pincode in the userobject (in one of its properties) but in a way that it isn't readable off course for authenticated users with LDAP tools but only
for the user self so that the propertie can be read from within sharepoint into the profile page (on the logged on users credentials).
Can anyone send us in the right direction, would be much appreciated.
Thanks,
Peter
You can also read that about delegating permissions in AD: http://social.technet.microsoft.com/wiki/contents/articles/20292.delegation-of-administration-in-active-directory.aspx
This posting is provided AS IS with no warranties or guarantees , and confers no rights.
Ahmed MALEK
My Website Link
My Linkedin Profile
My MVP Profile
Similar Messages
-
Loading values into drop down through properties file.
Hi all,
Can any one please let me know how to read a drop down through properties file I have two drop downs. I need to read the drop down values through the properties file .
I would appreciate if you can provide me with the sample code to do this(i mean similar kind of operation)
Say for example
if i have in the properties file
months.properties
Month = "january,february,march.....december"
january = "monday,tuesday, wednesday"
for the first drop down i need to load the months i.e., january, february, march etc.
After selecting the first drop down say january, then it should show me monday,tuesday and wednesday in the second drop down.
I know it's a begineers question. any help would be appreciated.
Thanks in advance for your help
regards,
samActually i want to use Jstl tag for this
<select name="secQst1">
<c:forEach var="flaglistdetail" items="${flaglist}">
<option value="<c:out value="${flaglistdetail.seqId}"/>"><c:out value="${flaglistdetail.seqDesc}"/></option>
</c:forEach>
</select>
The above operation is for getting the drop down values for the database. I want to hard code the values in the properties file and read it in the action and want to get it through the select tag.
private Properties _appConfig;
private static final String APP_CONFIG_NAME = "AppConfigProperties.properties";
if (_appConfig == null) {
_appConfig = new Properties();
try {
appConfig.load(FileUtil.getFileAsStream(APPCONFIG_NAME));
} catch (Exception e) {
throw new RuntimeException("can not find "
+ APP_CONFIG_NAME, e);
I was trying to do the above thing. but for some reason i couldn't get it.
if you have any sample code which does the same thing like this would be helpful -
Good morning,
I am trying to read a configuration file and then load its properties. I added a StringBuffered to be sure that the file was correct and it is. But at the moment to do the Properties load method, I don't get an exception and my Properties variable is empty.
I don't know if I am doing something wrong, this configuration file was already used in another application, so I am sure it is well encoding (ISO 8859-1).
Here my code
private Properties loadProperties(Properties p_props, String p_propertyFile) {
try {
FileInputStream inputStream = new FileInputStream(p_propertyFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder sb = new StringBuilder();
while((line = reader.readLine())!=null) {
sb.append(line).append("\n");
p_props.load(inputStream);
inputStream.close();
}catch(IOException ioe) {
m_log.error("Le fichier de properties est introuvable", ioe);
}return p_props;
}My properties file:
service.distribution.init.enabled=smtpDistributor
service.distribution.smtpDistributor.smtpHost=mail.company.com
Thank you in advance.
ElsyYou already read all lines into the buffer, so there is nothing left for p_props.load to read. Either reset or re-open the input stream or remove the buffer entirely.
-
Field: HowTo for private fields.
Hi;
Is there a way to get Field to reflect on private properties (no pun intended).
If declared public, no problem. But if private it throws no such field exception.
Thanks
-natIn case any of you care why I needed it, please see the following thread message#9.
http://forum.java.sun.com/thread.jsp?forum=31&thread=479517&start=0&range=15#2234020
And your input is most appreciated, especially criticism. Rather catch my bugs here....
Thanks
-nat -
Error 1013 private function, Help!?
Hey i'm new to this but i've been stuck on this problem for a couple of hours now.. If anybody can see what the problem is that would be great! I've highlighted the line on which the error occurs (line 68) I have my braces correct i believe so i can not see what the problem is. Thanks.
package {
import flash.display.Sprite;
import flash.text.TextField;
import Classes.P_Circle;
import flash.events.MouseEvent;
public class Main extends Sprite {
//private properties
private var container:Sprite = new Sprite ();
private var textBox:TextField = new TextField ();
private var padding:uint = 10;
//initialization
public function Main() {
//adds a random number of images to the contatiner
this.makeImages(getRandomNumber(10,5) );
//add a mouse listener to container
this.container.addEventListener(MouseEvent.CLICK, hitObject);
//add the container to the stage
stage.addChild(this.container);
//function to draw UI and config
this.ConfigUI();
private function ConfigUI():void {
this.textBox.x = 5;
this.textBox.y = -10;
stage.addChild(textBox);
//private methods, calculator
private function hitObject(e:MouseEvent):void {
//change transparancy of circle
e.target.alpha = 0.3;
//calculates new x and y for shapes
textBox.text = 'x ' + e.target.x + '. y:' + e.target.y;
private function makeImages(nImagesToCreate:uint):void {
var obj:P_Circle = new P_Circle(1,1);
// this is to keep the circles from colliding when randomly placed
var maxCols:Number = Math.floor(stage.stageWidth - obj.width - this.padding);
var maxRows:Number = Math.floor(stage.stageHeight - obj.height - 50);
obj = null;
//loop to create as many circles as asked
for (var j:uint = 0; j < nImagesToCreate; j++) {
//place circle in random posistions
obj = new P_Circle( getRandomNumber(maxCols, this.padding), getRandomNumber )
//give it a name
obj.name = 'circle_'+j;
//add it to container for display
this.container.addChild(obj);
obj = null;
// the sprite contaienr changes its size depending on objects which are on stage
trace ('container width: ', container.width);
trace ('container height: ', container.height);
private function getRandomNumber(upperLimit:uint, lowerLimit:uint):uint {
//get random number of circles
var randomNum:Number = Math.floor(Math.random() * (1 + 10 - 5) + 5);
return randomNum;Arent i telling it to just use randomnumber values within these parameters?
private function makeImages(nImagesToCreate:uint):void {
var obj:P_Circle1 = new P_Circle1(1,1);
// this is figures out where circles are placed, keeps them on screen
var maxCols:Number = Math.floor(stage.stageWidth - obj.width - this.padding);
var maxRows:Number = Math.floor(stage.stageHeight - obj.height - 50);
obj = null; -
Unable to retrieve server listen address through MBEAN API in Weblogic 10.3
Hi,
I am using weblogic 10.3 and i am lookign to retrive the listen address of the weblogic server where my application has been deployed. I have used the below piece of code to do that.
Code snippet :
======================================
private Properties loadXMLSchema(Properties cosbProps)
String serverName, serverPort, serverUrl;
Environment env = new Environment();
Hashtable ht = new Hashtable();
Context ctx = null;
try
ht.put(Context.SECURITY_PRINCIPAL,
cosbProps.getProperty("COSB.security.principal"));
ht.put(Context.SECURITY_CREDENTIALS,
cosbProps.getProperty("COSB.security.credentials"));
ctx = new InitialContext(ht);
MBeanHome home = MBeanHome)ctx.lookup(MBeanHome.LOCAL_JNDI_NAME);
serverName = home.getMBeanServer().getServerName();
Object mbeanArray[] =
home.getMBeansByType("ServerConfig").toArray();
int i = 0;
for (i = 0; i < mbeanArray.length; i++)
DynamicMBean mbean = (DynamicMBean)mbeanArray;
if (serverName.equals(mbean.getAttribute("Name")))
break;
DynamicMBean mbean = (DynamicMBean)mbeanArray[i];
serverPort =
mbean.getAttribute("ListenPort").toString();
serverUrl =
mbean.getAttribute("ListenAddress").toString();
Properties props = new Properties();
props.setProperty("port", serverPort);
props.setProperty("ipAddress", serverUrl);
return props;
catch (Exception ex)
System.out.println("exception in loadXMLSchema method" + ex);
return null;
======================================
This code is successfully running in wls 8.15 and i can able to see the listen address(ip address where weblogic server is running) in the JNDI information of weblogic server.
Now when i try this same piece of code in wls 10.3 , i am not able to see the listen address(ip address where weblogic server is running) in the JNDI information of weblogic server. The listen address is coming as NULL. I have tried to align the JMX specification in wls 10.3 by using the following argument in JDK startup option.
-Djmx.serial.form=1.0
But still the listen address is unable to reflect in JNDI specifcations of wls 10.3.
Would you please help in getting the listen address information in wls 10.3.
Thanks, Pralay
Edited by: ghoshp on Oct 12, 2011 11:35 AMjames.bayer wrote:
startManagedWebLogic should call setDomainEnv which should call commEnv
On Windows, mine is located here:
<WLS_11gPS1_Install>\wlserver_10.3\common\bin\commEnv.cmd
Looking at commEnv.sh it looks like you should be able to search for "SunOS" to see the section that specifies the locations of 64bit shared objects on your LD_LIBRARY_PATH.That is the first place that I looked.
Here's the code:
<pre>
SunOS)
arch=`uname -m`
if [ -n "${LD_LIBRARY_PATH}" ]; then
<snip>
if [ "${SUN_ARCH_DATA_MODEL}" = "64" ]; then
LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${WL_HOME}/server/native/solaris/sparc64:${WL_HOME}/server/native/solaris/sparc64/oci920_8
else
LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${WL_HOME}/server/native/solaris/sparc:${WL_HOME}/server/native/solaris/sparc/oci920_8
# LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${WL_HOME}/server/native/solaris/sparc64:${WL_HOME}/server/native/solaris/sparc/oci920_8
</pre>
Even when 64-bit is selected and WebLogic starts with a 64-bit JVM, it does not set the LD_LIBRARY_PATH accordingly. As you see I have even tried forcing the path - but even that didn't work. It seems to be overriding the value elsewhere.
One thing: what is the "vendor" supposed to be set as when using the Sun JBM? Sun? Oracle? I notice that further down the script it checks for "Oracle." -
Hi
My application is an interface to ldap directory. I have not used any ldap open source api to retrieve data from ldap. I have written connection pool that will help the application to connect to the ldap. It's working fine, but it's creating threads which are not invited.
ConnectionPool class takes care of the connection storage and creation, while Housekeeping thread relases these connection when idle after a given time.
Can someone please help in finding the problem in the code that creates additional threads.
package com.ba.cdLookup.manager;
import com.ba.cdLookup.exception.CDLookupException;
import com.ba.cdLookup.server.CdLookupProperties;
import java.util.Vector;
import javax.naming.Context;
import javax.naming.NamingException;
public class HouseKeeperThread extends Thread {
* Apache Logger to log erro/info/debug statements.
protected static org.apache.commons.logging.Log log = org.apache.axis.components.logger.LogFactory
.getLog(HouseKeeperThread.class.getName());
private static HouseKeeperThread houseKeeperThread;
* Close all connections existing.
* @param connections
* void
private void closeConnections(Vector connections) {
String methodIdentifier = "closeConnections";
int numOfConn = connections.size();
try {
for (int i = 0; i < numOfConn; i++) {
Context context = (Context) connections.get(i);
if (context != null) {
context.close();
context = null;
connections.remove(i);
numOfConn--;
log.info(" connection name:" + context
+ " removed. Threadcount =" + (connections.size()));
} catch (NamingException e) {
String errMsg = "CDLdapBuilder connect() - failure while releasing connection "
+ " Exception is " + e.toString();
log.error(errMsg);
} catch (Exception e) {
String errMsg = "CDLdapBuilder connect() - failure while releasing connection "
+ " Exception is " + e.toString();
log.error(errMsg);
* Thread run method
public void run() {
String methodIdentifier = "run";
try {
while(true){
log.debug("house keeping :" + this + " ---sleep");
//sleep(100000);
log.debug("house keeping :" + this + " startd after sleep");
sleep(CdLookupProperties.getHouseKeepConnectionTime());
ConnectionPool connectionPool = ConnectionPool
.getConnectionPool();
Vector connList = connectionPool.getAvailableConnections();
closeConnections(connList);
} catch (CDLookupException cde) {
log.error(methodIdentifier + " " + cde.getStackTrace());
} catch (InterruptedException ie) {
log.error(methodIdentifier + " " + ie.getStackTrace());
* @param connectionPool
* @return
* Thread
public static Thread getInstance() {
if(houseKeeperThread==null){
houseKeeperThread = new HouseKeeperThread();
return houseKeeperThread ;
package com.ba.cdLookup.manager;
import com.ba.cdLookup.exception.CDLookupException;
import com.ba.cdLookup.server.CdLookupProperties;
import com.ba.cdwebservice.schema.cdLookupPacket.LookupFailureReasons;
import java.util.Properties;
import java.util.Vector;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
* ConnectionPool class manages, allocates LDAP connections. It works as a lazy
* binder and retrieves connections only when required. It doesn't allow
* connection greater then the maximum connection stated.
* To retrieve a connection the singelton method getConnectionPool is to used,
* which retruns thread safe singleton object for the connection.
public class ConnectionPool implements Runnable {
private int initialConnections = 0;
private int maxConnections = 0;
private boolean waitIfBusy = false;
private Vector availableConnections, busyConnections;
private boolean connectionPending = false;
private static int threadCount = 0;
* classIdentifier
private final String classIdentifier = "ConnectionPool";
* Apache Logger to log erro/info/debug statements.
protected static org.apache.commons.logging.Log log = org.apache.axis.components.logger.LogFactory
.getLog(CDLdapBuilder.class.getName());
* To get the attribute a systemaccessfor out of the search result
private String vendorContextFactoryClass = "com.sun.jndi.ldap.LdapCtxFactory";// "com.ibm.jndi.LDAPCtxFactory";
* context factory to use
private String ldapServerUrl = "LDAP://test.ldap.com"; // default ldap
* server live used by default
private String searchBase;
* environment properties.
private Properties env;
* DirContext
private javax.naming.directory.DirContext ctx;
* default search base to be used in Corporate Directory searches
private String defaultSearchBase = "dc=Pathway";
* search criteria
private String searchAttributes;
* search filter to retrieve data from CD
private String searchFilter;
* CorporateDirectoryLookup Constructor
* <p>
* loads the setup parameters from the properties file and stores them
* Makes a connection to the directory and sets default search base
* @throws CDLookupException
* @throws CDLookupException
private ConnectionPool() throws CDLookupException {
this.maxConnections = CdLookupProperties.getMaxConnection();// maxConnections;
this.initialConnections = CdLookupProperties.getInitialConnection();
this.waitIfBusy = CdLookupProperties.isWaitIfBusy();
this.searchBase = CdLookupProperties.getDefaultSearchBase();
//for local env testing
// this.maxConnections = 5;
// this.initialConnections = 1;
// this.waitIfBusy = true;
* For keeping no of connections in the connection pool if
* (initialConnections > maxConnections) { initialConnections =
* maxConnections; }
availableConnections = new Vector(maxConnections);
busyConnections = new Vector(maxConnections);
for (int i = 0; i < maxConnections; i++) {
availableConnections.add(makeNewConnection());
* ConnectionPoolHolder provide Thread safe singleton
* instance of ConnectionPool class
private static class ConnectionPoolHolder {
* connection pool instance
private static ConnectionPool connectionPool = null;
* If no ConnectionPool object is present, it creates instance of
* ConnectionPool class and initiates thread on that.
* @return ConnectionPool Returns singleton object of ConnectionPool
* class.
* @throws CDLookupException
private static ConnectionPool getInstance() throws CDLookupException {
if (connectionPool == null) {
connectionPool = new ConnectionPool();
new Thread(connectionPool).start();
// Initiate house keeping thread.
HouseKeeperThread.getInstance().start();
return connectionPool;
* Returns singleton object of ConnectionPool class.
* @return ConnectionPool
* @throws CDLookupException
public static ConnectionPool getConnectionPool() throws CDLookupException {
return ConnectionPoolHolder.getInstance();
* getConnection retrieves connections to the corp directory. In case
* there is no available connections in the pool then it'll try to
* create one, if the max connection limit for the connection pool
* reaches then this waits to retrieve one.
* @return Context
* @throws CDLookupException
public synchronized Context getConnection() throws CDLookupException {
String methodIdentifier = "getConnection";
if (!availableConnections.isEmpty()) {
int connectionSize = availableConnections.size() - 1;
DirContext existingConnection = (DirContext) availableConnections
.get(connectionSize);
availableConnections.remove(connectionSize);
* If connection on available list is closed (e.g., it timed
* out), then remove it from available list and repeat the
* process of obtaining a connection. Also wake up threads that
* were waiting for a connection because maxConnection limit was
* reached.
if (existingConnection == null) {
notifyAll(); // Freed up a spot for anybody waiting
return (getConnection());
} else {
busyConnections.add(existingConnection);
return (existingConnection);
} else {
* Three possible cases: 1) You haven't reached maxConnections
* limit. So establish one in the background if there isn't
* already one pending, then wait for the next available
* connection (whether or not it was the newly established one).
* 2) You reached maxConnections limit and waitIfBusy flag is
* false. Throw SQLException in such a case. 3) You reached
* maxConnections limit and waitIfBusy flag is true. Then do the
* same thing as in second part of step 1: wait for next
* available connection.
if ((totalConnections() < maxConnections) && !connectionPending) {
makeBackgroundConnection();
} else if (!waitIfBusy) {
throw new CDLookupException("Connection limit reached", 0);
* Wait for either a new connection to be established (if you
* called makeBackgroundConnection) or for an existing
* connection to be freed up.
try {
wait();
} catch (InterruptedException ie) {
String errMsg = "Exception raised =" + ie.getStackTrace();
log.error(errMsg);
throw new CDLookupException(classIdentifier, methodIdentifier,
errMsg, ie);
// connection freed up, so try again.
return (getConnection());
* You can't just make a new connection in the foreground when none are
* available, since this can take several seconds with a slow network
* connection. Instead, start a thread that establishes a new
* connection, then wait. You get woken up either when the new
* connection is established or if someone finishes with an existing
* connection.
private void makeBackgroundConnection() {
connectionPending = true;
try {
Thread connectThread = new Thread(this);
log.debug("background thread created");
connectThread.start();
} catch (OutOfMemoryError oome) {
log.error("makeBackgroundConnection ="+ oome.getStackTrace());
* Thread run method
public void run() {
String methodIdentifier = "run";
try {
Context connection = makeNewConnection();
synchronized (this) {
availableConnections.add(connection);
connectionPending = false;
notifyAll();
} catch (Exception e) { // SQLException or OutOfMemory
// Give up on new connection and wait for existing one
// to free up.
String errMsg = "Exception raised =" + e.getStackTrace();
log.error(errMsg);
* This explicitly makes a new connection. Called in the foreground when
* initializing the ConnectionPool, and called in the background when
* running.
* @return Context
* @throws CDLookupException
private Context makeNewConnection() throws CDLookupException {
String methodIdentifier = "makeNewConnection";
Context context = null;
env = new Properties();
log.debug("inside " + methodIdentifier);
try {
env.put(Context.INITIAL_CONTEXT_FACTORY,
getVendorContextFactoryClass());
env.put(Context.PROVIDER_URL, getLdapServerUrl());
env.put("com.sun.jndi.ldap.connect.pool", "true");
context = new InitialDirContext(env);
} catch (NamingException e) {
String errMsg = "CDLdapBuilder connect() - failure while attempting to contact "
+ ldapServerUrl + " Exception is " + e.toString();
throw new CDLookupException(classIdentifier, methodIdentifier,
errMsg, e, LookupFailureReasons.serviceUnavailable);
} catch (Exception e) {
String errMsg = "CDLdapBuilder connect() - failure while attempting to contact "
+ ldapServerUrl + " Exception is " + e.toString();
throw new CDLookupException(classIdentifier, methodIdentifier,
errMsg, e, LookupFailureReasons.serviceUnavailable);
log.info("new connection :" + (threadCount++) + " name =" + context);
log.debug("exit " + methodIdentifier);
return context;
* releases connection to the free pool
* @param context
public synchronized void free(Context context) {
busyConnections.remove(context);
availableConnections.add(context);
// Wake up threads that are waiting for a connection
notifyAll();
* @return int give total no of avail connections.
public synchronized int totalConnections() {
return (availableConnections.size() + busyConnections.size());
* Close all the connections. Use with caution: be sure no connections
* are in use before calling. Note that you are not <I>required</I> to
* call this when done with a ConnectionPool, since connections are
* guaranteed to be closed when garbage collected. But this method gives
* more control regarding when the connections are closed.
public synchronized void closeAllConnections() {
closeConnections(availableConnections);
availableConnections = new Vector();
closeConnections(busyConnections);
busyConnections = new Vector();
* Close all connections existing.
* @param connections
* void
private void closeConnections(Vector connections) {
String methodIdentifier = "closeConnections";
try {
for (int i = 0; i < connections.size(); i++) {
Context context = (Context) connections.get(i);
if (context != null) {
log.info(" connection name:" + context
+ " removed. Threadcount =" + (threadCount++));
context.close();
context = null;
} catch (NamingException e) {
String errMsg = "CDLdapBuilder connect() - failure while attempting to contact "
+ ldapServerUrl + " Exception is " + e.toString();
log.error(errMsg);
public synchronized String toString() {
String info = "ConnectionPool(" + getLdapServerUrl() + ","
+ getVendorContextFactoryClass() + ")" + ", available="
+ availableConnections.size() + ", busy="
+ busyConnections.size() + ", max=" + maxConnections;
return (info);
* @return the defaultSearchBase
public final String getDefaultSearchBase() {
return defaultSearchBase;
* @param defaultSearchBase
* the defaultSearchBase to set
public final void setDefaultSearchBase(String defaultSearchBase) {
this.defaultSearchBase = defaultSearchBase;
* @return the ldapServerUrl
public final String getLdapServerUrl() {
return ldapServerUrl;
* @param ldapServerUrl
* the ldapServerUrl to set
public final void setLdapServerUrl(String ldapServerUrl) {
this.ldapServerUrl = ldapServerUrl;
* @return the vendorContextFactoryClass
public final String getVendorContextFactoryClass() {
return vendorContextFactoryClass;
* @param vendorContextFactoryClass
* the vendorContextFactoryClass to set
public final void setVendorContextFactoryClass(
String vendorContextFactoryClass) {
this.vendorContextFactoryClass = vendorContextFactoryClass;
* @return the availableConnections
public final Vector getAvailableConnections() {
return availableConnections;
}Hi,
As the connection pool implmentation has the bug of not extending more than the min size, workaround I use is MIN_CONN=100 and MAX_CONN=101,and just waiting for the bug to get fixed. (using Netscape SDK for java4.0) -
Composite control - change text property of textbox from .cs file
Hi All,
I have created a composite control with dropdowns and hiddenfield for datepicker. Now when I change the value of dropdown from browser - client side then its value is retained on postback. But when I change value programmatically its not reflected on
screen.
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.ComponentModel;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
namespace GOV.Framework.Portal.Controls
/// <summary>
/// Simple DateTimePicker control that uses jQuery UI DatePicker to pop up
/// a date, time or both picker.
/// </summary>
[ToolboxBitmap(typeof(System.Web.UI.WebControls.Calendar)), DefaultProperty("SelectedValue"),
ToolboxData("<{0}:DateTimePicker runat=\"server\"></{0}:DateTimePicker>"), PersistenceMode(PersistenceMode.InnerProperty)]
public class DateTimePicker : WebControl
#region "Global Variables"
public enum DisplayControls
TextBox,
Dropdown
public enum DisplayModes
Button,
ImageButton,
AutoPopup,
Inline,
public enum DisplayTypes
Time,
Date,
DateTime
public enum DisplayMonthTypes
Full,
Short
private enum DisplayYearTypes
Full,
Short
private DropDownList ddlDay = new DropDownList();
private DropDownList ddlMonth = new DropDownList();
private DropDownList ddlYear = new DropDownList();
private TextBox txtDate = new TextBox();
private Label lblMsg = new Label();
private System.Web.UI.WebControls.Image imgCal = new System.Web.UI.WebControls.Image();
private HiddenField hdnDate = new HiddenField();
private DisplayModes _DisplayMode = DisplayModes.ImageButton;
private DisplayControls _DisplayControl = DisplayControls.TextBox;
private DisplayTypes _DisplayType = DisplayTypes.DateTime;
private int _StepMinutes = 1;
private int _StepHours = 1;
private DateTime? _MinDate = null;
private DateTime? _MaxDate = null;
private string _OnClientSelect = "";
private string _ButtonImage = "../Images/calendar.png";
private string _CalendarCss = "WebResource";
private string _CalendarJs = "../scripts/timepicker.js";
private DisplayMonthTypes _DisplayMonthType = DisplayMonthTypes.Full;
private DisplayYearTypes _DisplayYearType = DisplayYearTypes.Full;
private int _minYear = DateTime.Now.Year - 25;
private int _maxYear = DateTime.Now.Year;
private int _minMonth = 1;
private int _maxMonth = 31;
private int _minDay = 1;
private int _maxDay = 28;
private string _dateControlClientId = string.Empty;
DateTime? _SelectedDate = null;
private bool _DisplayMessageLabel = true;
private short _tabIndex;
private const string vwst_SelectedDate = "_SelectedDate";
#region "ErrorMessages"
private const string SelectedDate_GreaterThan_MaxDate = "SelectedDate can not be greater than MaxDate";
private const string MaxDate_LessThan_SelectedDate = "MaxDate can not be less than SelectedDate";
private const string SelectedDate_LessThan_MinDate = "SelectedDate can not be less than MinDate";
private const string MinDate_GreaterThan_SelectedDate = "MinDate can not be greater than SelectedDate";
#endregion
#endregion
#region "Properties"
#region "Private Properties"
[Description("Determines display full or short(yy) year")]
[Category("DateTime Selection"), DefaultValue(typeof(DisplayTypes), "string")]
private DisplayYearTypes DisplayYearType
get
return _DisplayYearType;
set
_DisplayYearType = value;
[Description("Determines minimum year to be displayed in dropdown : Default currentyear - 25")]
[Category("DateTime Selection"), DefaultValue(typeof(DisplayTypes), "int")]
private int MinYear
get
if (MinDate != null)
_minYear = MinDate.Value.Year;
else
_minYear = DateTime.Now.Year - 25;
return _minYear;
//set
// _minDisplayYear = value;
[Description("Determines maximum year to be displayed in dropdown : Default currentyear")]
[Category("DateTime Selection"), DefaultValue(typeof(DisplayTypes), "int")]
private int MaxYear
get
if (MaxDate != null)
_maxYear = MaxDate.Value.Year;
else
_maxYear = DateTime.Now.Year;
return _maxYear;
//set
// _maxDisplayYear = value;
private string DateControlClientId
get
if (DisplayControl == DisplayControls.Dropdown)
_dateControlClientId = hdnDate.ClientID;
else
_dateControlClientId = txtDate.ClientID;
return _dateControlClientId;
[Description("Determines minimum month of min date : default 1")]
[Category("DateTime Selection"), DefaultValue(1)]
private int minMonth
get
if (MinDate != null)
_minMonth = MinDate.Value.Month;
else
_minMonth = 1;
return _minMonth;
[Description("Determines max months of max date: Default 12")]
[Category("DateTime Selection"), DefaultValue(12)]
private int maxMonth
get
if (MaxDate != null)
_maxMonth = MaxDate.Value.Month;
else
_maxMonth = 1;
return _maxMonth;
[Description("Determines minimum day : Defualt 1")]
[Category("DateTime Selection"), DefaultValue(1)]
private int minDay
get
if (MinDate != null)
_minDay = MinDate.Value.Day;
else
_minDay = 1;
return _minDay;
[Description("Determines max day: Defualt last day of max month")]
[Category("DateTime Selection"), DefaultValue(30)]
private int maxDay
get
if (MaxDate != null)
_maxDay = MaxDate.Value.Day;
else
_maxDay = DateTime.DaysInMonth(MaxYear, maxMonth);
return _maxDay;
#endregion
#region "Public Properties"
/// <summary>
/// The currently selected datetime
/// </summary>
[Category("DateTime Selection")]
public DateTime? SelectedValue
get
DateTime dt = new DateTime();
if (DisplayControl == DisplayControls.TextBox && txtDate.Text != "")
DateTime.TryParse(txtDate.Text, out dt);
else if (DisplayControl == DisplayControls.Dropdown && hdnDate.Value != "")
DateTime.TryParse(hdnDate.Value, out dt);
if (dt != null && dt != new DateTime())
_SelectedDate = dt;
else
_SelectedDate = null;
return _SelectedDate;
set
if (!value.HasValue)
txtDate.Text = "";
hdnDate.Value = "";
else
if (value != null && MinDate != null && value < MinDate)
throw new ArgumentOutOfRangeException("SelectedValue", SelectedDate_LessThan_MinDate);
if (value != null && MaxDate != null && value > MaxDate)
throw new ArgumentOutOfRangeException("SelectedValue", SelectedDate_GreaterThan_MaxDate);
string dateFormat = this.DateTimeFormat;
//if ( dateFormat == "Auto")
// dateFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
if (DisplayControl == DisplayControls.TextBox)
txtDate.Text = value.Value.ToString(dateFormat);
else if (DisplayControl == DisplayControls.Dropdown)
hdnDate.Value = value.Value.ToString(dateFormat);
_SelectedDate = value;
if (DisplayControl == DisplayControls.Dropdown)
setDropDownValue(value);
[Description("Determines display textbox or dropdowns")]
[Category("DateTime Selection"), DefaultValue(typeof(DisplayModes), "TextBox")]
public DisplayControls DisplayControl
get { return _DisplayControl; }
set { _DisplayControl = value; }
[Description("Determines how the datepicking option is activated")]
[Category("DateTime Selection"), DefaultValue(typeof(DisplayModes), "ImageButton")]
public DisplayModes DisplayMode
get { return _DisplayMode; }
set { _DisplayMode = value; }
[Description("Determines what datetimepicker should return")]
[Category("DateTime Selection"), DefaultValue(typeof(DisplayTypes), "DateTime")]
public DisplayTypes DisplayType
get
return _DisplayType;
set
_DisplayType = value;
[Description("Increment minute factor when using the time picker.")]
[Category("DateTime Selection"), DefaultValue(1)]
public int StepMinutes
get
return _StepMinutes;
set
_StepMinutes = value;
[Description("Increment hour factor when using the time picker.")]
[Category("DateTime Selection"), DefaultValue(1)]
public int StepHours
get
return _StepHours;
set
_StepHours = value;
private string _DateTimeFormat = CultureInfo.CurrentCulture != null ? CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern : "dd/MM/yyyy";
[Description("Determines the Date Format used. Auto uses CurrentCulture.DateTimeFormat.ShortDatePattern. Format: MM month, dd date, yyyy year symbol")]
[Category("DateTime Selection"), DefaultValue("dd/MM/yyyy")]
public string DateTimeFormat
get
return _DateTimeFormat;
set
_DateTimeFormat = value;
[Description("Minumum allowable date. Leave blank to allow any date")]
[Category("DateTime Selection"), DefaultValue(typeof(DateTime?), null)]
public DateTime? MinDate
get
return _MinDate;
set
if (value != null && SelectedValue != null && value > SelectedValue)
throw new ArgumentOutOfRangeException("MinDate", MinDate_GreaterThan_SelectedDate);
_MinDate = value;
[Description("Maximum allowable date. Leave blank to allow any date.")]
[Category("DateTime Selection"), DefaultValue(typeof(DateTime?), null)]
public DateTime? MaxDate
get
return _MaxDate;
set
if (value != null && SelectedValue != null && value < SelectedValue)
throw new ArgumentOutOfRangeException("MaxDate", MaxDate_LessThan_SelectedDate);
_MaxDate = value;
[Description("Client event handler fired when a date is selected")]
[Category("DateTime Selection"), DefaultValue("")]
public string OnClientSelect
get
return _OnClientSelect;
set
_OnClientSelect = value;
[Description("Url to a Calendar Image. Applies only if the DisplayMode = ImageButton")]
[Category("DateTime Resource"), DefaultValue("../Images/calendar.png")]
public string ButtonImage
get { return _ButtonImage; }
set { _ButtonImage = value; }
[Category("DateTime Resource"), Description("The CSS that is used for the calendar or empty for default."), DefaultValue("WebResource")]
public string CalendarCss
get { return _CalendarCss; }
set { _CalendarCss = value; }
[Description("Location for the calendar JavaScript or empty for default.")]
[Category("DateTime Resource"), DefaultValue("../scripts/timepicker.js")]
public string CalendarJs
get { return _CalendarJs; }
set { _CalendarJs = value; }
[Description("Determines what to Display full Month name or short month name")]
[Category("DateTime Selection"), DefaultValue(typeof(DisplayTypes), "string")]
public DisplayMonthTypes DisplayMonthType
get
return _DisplayMonthType;
set
_DisplayMonthType = value;
[Description("Display static label for msg below date control")]
[Category("DateTime Selection"), DefaultValue(true)]
public bool DisplayMessageLable
get { return _DisplayMessageLabel; }
set { _DisplayMessageLabel = value; }
[Bindable(true)]
[DefaultValue("false")]
public override short TabIndex
get
return _tabIndex;
set
_tabIndex = value;
ddlDay.TabIndex = value;
ddlMonth.TabIndex = value;
ddlYear.TabIndex = value;
imgCal.TabIndex = value;
#endregion
#endregion
#region "Events"
public DateTimePicker()
this.Width = Unit.Pixel(80);
/// <summary>
/// Load all controls
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
base.OnInit(e);
//Controls.Clear();
//CreateAndAddControls();
/// <summary>
/// Add Child controls - Dropdowns and textbox;
/// </summary>
protected override void CreateChildControls()
base.CreateChildControls();
Controls.Clear();
CreateAndAddControls();
/// <summary>
/// Load all controls
/// </summary>
/// <param name="e"></param>
protected override void OnLoad(EventArgs e)
base.OnLoad(e);
if (DisplayControl == DisplayControls.Dropdown)
if (ddlDay.Items.Count == 0 || ddlMonth.Items.Count == 0 || ddlYear.Items.Count == 0 || !Page.IsPostBack)
FillDropdowns();
generateDisplayMessage();
protected override void LoadViewState(object savedState)
base.LoadViewState(savedState);
protected override void LoadControlState(object savedState)
base.LoadControlState(savedState);
protected override object SaveViewState()
if (HasControls() && Page.IsPostBack)
ddlDay.SelectedValue = "11";
object obj = base.SaveViewState();
return obj;
protected override void TrackViewState()
base.TrackViewState();
/// <summary>
/// Most of the work happens here for generating the hook up script code
/// </summary>
/// <param name="e"></param>
protected override void OnPreRender(EventArgs e)
base.OnPreRender(e);
// Register resources
this.RegisterResources();
string script = GenerateScript();
Page.ClientScript.RegisterStartupScript(this.GetType(), "_cal" + this.ID, script, true);
/// <summary>
/// Render Control
/// </summary>
/// <param name="writer"></param>
public override void RenderControl(HtmlTextWriter writer)
if (this.DisplayMode != DisplayModes.Inline)
base.RenderControl(writer);
else
writer.Write("<div id='" + this.ClientID + "Div'></div>");
if (HttpContext.Current == null)
if (this.DisplayMode == DisplayModes.Button)
writer.Write(" <input type='button' value='...' style='width: 20px; height: 20px;' />");
else if ((this.DisplayMode == DisplayModes.ImageButton))
string img;
if (this.ButtonImage == "WebResource")
img = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "jQueryDatePicker.Resources.calendar.png");
else
img = this.ResolveUrl(this.ButtonImage);
writer.AddAttribute(HtmlTextWriterAttribute.Src, img);
writer.AddAttribute("hspace", "2");
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
/// <summary>
/// Render Control
/// </summary>
/// <param name="writer"></param>
protected override void Render(HtmlTextWriter writer)
RenderControls(writer);
#endregion
#region "Methods"
/// <summary>
/// Set properties of control
/// </summary>
private void CreateAndAddControls()
txtDate.ID = "_txtDate";
txtDate.CssClass = "dpDate";
ddlDay.ID = "_ddlDay";
ddlMonth.ID = "_ddlMonth";
ddlYear.ID = "_ddlYear";
imgCal.ID = "_imgCal";
imgCal.CssClass = "trigger";
imgCal.ImageUrl = this.ButtonImage;
//imgCal.Visible = false;
hdnDate.ID = "_hdnDate";
lblMsg.ID = "_lblMsg";
lblMsg.CssClass = "MsgLabel";
if (DisplayControl == DisplayControls.Dropdown)
txtDate.Visible = false;
this.Controls.Add(ddlDay);
this.Controls.Add(ddlMonth);
this.Controls.Add(ddlYear);
this.Controls.Add(hdnDate);
else
txtDate.Visible = true;
this.Controls.Add(txtDate);
this.Controls.Add(imgCal);
this.Controls.Add(lblMsg);
/// <summary>
/// Add Controls to the control
/// </summary>
private void RenderControls(HtmlTextWriter writer)
//if (ChildControlsCreated)
// return;
AddAttributesToRender(writer);
writer.AddAttribute(HtmlTextWriterAttribute.Class, "datePickerTable", false);
writer.RenderBeginTag(HtmlTextWriterTag.Table);//start of table
writer.RenderBeginTag(HtmlTextWriterTag.Tr);//start of tr1
if (DisplayControl == DisplayControls.Dropdown)
writer.RenderBeginTag(HtmlTextWriterTag.Td);
ddlDay.RenderControl(writer);
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
ddlMonth.RenderControl(writer);
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
ddlYear.RenderControl(writer);
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
hdnDate.RenderControl(writer);
writer.RenderEndTag();
else
writer.RenderBeginTag(HtmlTextWriterTag.Td);
txtDate.RenderControl(writer);
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
//Control ltrl1 = new LiteralControl();
//writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "None");
//writer.RenderBeginTag(HtmlTextWriterTag.Div);
////ltrl1.RenderControl(writer);
//imgCal.RenderControl(writer);
//writer.RenderEndTag();//end of div
writer.Write("<div style=\"display:none\">");
imgCal.RenderControl(writer);
writer.Write("</div>");
writer.RenderEndTag();
writer.RenderEndTag();//end of tr1
writer.RenderBeginTag(HtmlTextWriterTag.Tr);//start of tr
writer.AddAttribute(HtmlTextWriterAttribute.Colspan, "4", false);
writer.RenderBeginTag(HtmlTextWriterTag.Td);
lblMsg.RenderControl(writer);
writer.RenderEndTag();
writer.RenderEndTag();// end of tr2
writer.RenderEndTag();// end of table
//string newTable = "<table class='datePickerTable'";
//string endTable = "</table>";
//string newTr = "<tr>";
//string endTr = "</tr>";
//string newTd = "<td>";
//string endTd = "</td>";
////Controls.Clear();
//InitControls();
//Controls.Add(new LiteralControl(newTable + newTr + newTd));
//if (DisplayControl == DisplayControls.Dropdown)
// Controls.Add(ddlDay);
// Controls.Add(new LiteralControl(endTd + newTd));
// Controls.Add(ddlMonth);
// Controls.Add(new LiteralControl(endTd + newTd));
// Controls.Add(ddlYear);
// Controls.Add(new LiteralControl(endTd + newTd));
//Controls.Add(txtDate);
//Controls.Add(hdnDate);
//Controls.Add(new LiteralControl(endTd + newTd));
//Controls.Add(new LiteralControl("<div style=\"display:none\">"));
//Controls.Add(imgCal);
//Controls.Add(new LiteralControl("</div>"));
//Controls.Add(new LiteralControl(endTd + endTr));
//Controls.Add(new LiteralControl(newTr + "<td colspan=4>"));
//Controls.Add(lblMsg);
//Controls.Add(new LiteralControl(endTd + endTr + endTable));
/// <summary>
/// Code that embeds related resources (.js and css)
/// </summary>
/// <param name="scriptProxy"></param>
protected void RegisterResources()
// Load the calandar script
string script = this.CalendarJs;
// Load jQuery Calendar Scripts
if (script == "WebResource")
Page.ClientScript.RegisterClientScriptResource(this.GetType(), "jQueryDatePicker.Resources.ui.datepicker.js");
else if (!string.IsNullOrEmpty(script))
Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "__jqueryCalendar", this.ResolveUrl(script));
// Load the related CSS reference into the page
script = this.CalendarCss;
if (script == "WebResource")
script = Page.ClientScript.GetWebResourceUrl(this.GetType(), "jQueryDatePicker.Resources.ui.datepicker.css");
else if (!string.IsNullOrEmpty(script))
script = this.ResolveUrl(this.CalendarCss);
// Register Calendar CSS 'manually'
string css = @"<link href=""" + script + @""" type=""text/css"" rel=""stylesheet"" />";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "_calcss", css, false);
/// <summary>
/// Converts a date to a JavaScript date string in UTC format
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
private static string EncodeJsDate(DateTime date)
return "new Date(\"" + date.ToString("U") + " UTC" + "\")";
/// <summary>
/// Generate Javascript for Datepicker plugin
/// </summary>
/// <returns></returns>
private string GenerateScript()
// To capture and map the various option parameters
StringBuilder sbOptions = new StringBuilder(512);
sbOptions.Append("{");
//jQuey Script
StringBuilder sbStartupScript = new StringBuilder(400);
sbStartupScript.AppendLine("jQuery(document).ready( function() {");
string dateFormat = this.DateTimeFormat;
if (!string.IsNullOrEmpty(dateFormat))
dateFormat = this.DateTimeFormat.Replace("MMM", "M").Replace("MM", "mm");
sbOptions.Append("dateFormat: '" + dateFormat + "'");
//string onSelect = this.OnClientSelect;
if (this.DisplayMode == DisplayModes.Button)
sbOptions.Append(",showOnFocus: false, showTrigger: '<button type=\"button\" class=\"trigger\">...</button>'");
else if (this.DisplayMode == DisplayModes.ImageButton)
string img = this.ButtonImage;
if (img == "WebResource")
img = Page.ClientScript.GetWebResourceUrl(this.GetType(), "jQueryDatePicker.Resources.calendar.png");
else
img = this.ResolveUrl(this.ButtonImage);
sbOptions.Append(",showOnFocus: false, showTrigger: '#" + imgCal.ClientID + "'");
sbOptions.Append(", onSelect: DateSelectedFromCalendar ");
if (this.MinDate.HasValue)
sbOptions.Append(",minDate: new Date(" + MinDate.Value.Year.ToString() + "," + (MinDate.Value.Month - 1).ToString() + "," + MinDate.Value.Day.ToString() + ")");
if (this.MaxDate.HasValue)
sbOptions.Append(",maxDate: new Date(" + MaxDate.Value.Year.ToString() + "," + (MaxDate.Value.Month - 1).ToString() + "," + MaxDate.Value.Day.ToString() + ")");
sbOptions.Append(",yearRange:' " + this.MinYear.ToString() + ":" + this.MaxYear.ToString() + "'");
//end of options
sbOptions.Append("}");
// Write out initilization code for calendar
if (this.DisplayMode != DisplayModes.Inline)
sbStartupScript.AppendLine("var cal = jQuery('#" + this.DateControlClientId + "').datepick(" + sbOptions.ToString() + ");");
else
sbStartupScript.AppendLine("var cal = jQuery('#" + this.ClientID + "Div').datepick(" + sbOptions.ToString() + ");");
sbStartupScript.AppendLine("var dp = jQuery.datepicker;");
if (this.SelectedValue.HasValue && this.SelectedValue.Value > new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc))
sbStartupScript.AppendLine("dp.setDateFor(cal[0],new Date('" + txtDate.Text + "'));");
sbStartupScript.AppendLine("dp.reconfigureFor(cal[0]);");
//******************* When dropdown changes then reflect it in calendar
if (DisplayControl == DisplayControls.Dropdown)
sbStartupScript.AppendLine("\r\n\r");
sbStartupScript.Append("$('#" + ddlDay.ClientID);
sbStartupScript.Append(",#" + ddlMonth.ClientID);
sbStartupScript.Append(",#" + ddlYear.ClientID + "').change(function() {");
// disable months and days when they are less then day months of minimum date
sbStartupScript.Append("$ddlDay=$('#" + ddlDay.ClientID + "');");
sbStartupScript.Append("$ddlMonth=$('#" + ddlMonth.ClientID + "');");
sbStartupScript.Append("$ddlYear=$('#" + ddlYear.ClientID + "');");
sbStartupScript.AppendLine("var minYear=" + this.MinYear.ToString() + ";");
///disable months of minimum year which are less then minumum date month
sbStartupScript.AppendLine("if($ddlYear.val()<=minYear && $('#" + this.DateControlClientId + "').val!=''){ alert('true');");
sbStartupScript.AppendLine("var minMonth=" + this.minMonth.ToString() + ";");
sbStartupScript.AppendLine("if($ddlMonth.val()<=minMonth){");//start of if of minMonth
sbStartupScript.AppendLine("$ddlMonth.val(minMonth);");
sbStartupScript.AppendLine("var minDay=" + this.minDay.ToString() + ";");
sbStartupScript.AppendLine("$ddlMonth.find('option:lt('+minMonth+')').hide();");
sbStartupScript.AppendLine("if($ddlDay.val()<=minDay)");
sbStartupScript.AppendLine("$ddlDay.val(minDay);");
sbStartupScript.AppendLine("}");// end of if of minMonth
sbStartupScript.AppendLine("else {");
sbStartupScript.AppendLine("$ddlDay.find('option').show();");
sbStartupScript.AppendLine("}");// end of else part of min month
sbStartupScript.AppendLine("$ddlDay.find('option:lt('+minDay+')').hide();");
sbStartupScript.AppendLine("}");// end of if part of min Year
sbStartupScript.AppendLine("else {");
sbStartupScript.AppendLine("$ddlMonth.find('option').show();");
sbStartupScript.AppendLine("}");// end of else part of min Year
///set date in calendar
sbStartupScript.AppendLine();
sbStartupScript.Append("$('#" + this.DateControlClientId + "').datepick('setDate', new Date(\n\r\r ");
sbStartupScript.Append("$('#" + ddlYear.ClientID + "').val(),");
sbStartupScript.Append("$('#" + ddlMonth.ClientID + "').val()-1,");
sbStartupScript.Append("$('#" + ddlDay.ClientID + "').val()));");
sbStartupScript.AppendLine("} );");
//******************* When calendar changes then reflect it in dropdown
sbStartupScript.AppendLine("\r\n\r");
sbStartupScript.AppendLine("function DateSelectedFromCalendar(dates) {");
if (DisplayControl == DisplayControls.Dropdown)
sbStartupScript.AppendLine("$('#" + ddlDay.ClientID + "').val(dates.length ? dates[0].getDate() : '');");
sbStartupScript.AppendLine("$('#" + ddlMonth.ClientID + "').val(dates.length ? dates[0].getMonth() +1 : '');");
sbStartupScript.AppendLine("$('#" + ddlYear.ClientID + "').val(dates.length ? dates[0].getFullYear() : '');");
if (!string.IsNullOrEmpty(this.OnClientSelect))
sbStartupScript.AppendLine(this.OnClientSelect + "();");
sbStartupScript.AppendLine("}");
//******************* Validation Script
sbStartupScript.AppendLine("\r\n\r");
sbStartupScript.AppendLine("$('form').validate({");
sbStartupScript.AppendLine("errorPlacement: $.datepick.errorPlacement,");
sbStartupScript.AppendLine("rules: {");
sbStartupScript.AppendLine(this.DateControlClientId + ": {");//start of format picker
sbStartupScript.AppendLine("required: true, dpDate: true}");//end of formate picker
sbStartupScript.AppendLine("}, ");// end of rules
sbStartupScript.AppendLine("messages: {");
sbStartupScript.AppendLine(this.DateControlClientId + ": 'Please enter a valid date (" + this.DateTimeFormat + ")'");
sbStartupScript.AppendLine("}");// end of messages
sbStartupScript.AppendLine("});"); //end of validate function
//******************* close document ready function
sbStartupScript.AppendLine("} );");
return sbStartupScript.ToString();
/// <summary>
/// Fill day month and year dropdown
/// </summary>
private void FillDropdowns()
//Fill Day Dropdown
ListItem liDay = new ListItem("Day", "0");
ddlDay.Items.Add(liDay);
for (int i = 1; i <= 31; i++)
ListItem li = new ListItem(i.ToString(), i.ToString());
ddlDay.Items.Add(li);
//Fill Month Dropdown
ListItem liMonth = new ListItem("Month", "0");
ddlMonth.Items.Add(liMonth);
string monthName = string.Empty;
for (int i = 1; i <= 12; i++)
switch (DisplayMonthType)
case DisplayMonthTypes.Full:
monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i);
break;
case DisplayMonthTypes.Short:
monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(i);
break;
ListItem li = new ListItem(monthName, i.ToString());
ddlMonth.Items.Add(li);
//Fill Year Dropdown
ListItem liYear = new ListItem("Year", "0");
ddlYear.Items.Add(liYear);
string yearDisplay = string.Empty;
for (int i = MinYear; i <= MaxYear; i++)
switch (DisplayYearType)
case DisplayYearTypes.Full:
yearDisplay = i.ToString();
break;
case DisplayYearTypes.Short:
yearDisplay = i.ToString().Substring(2);
break;
ListItem li = new ListItem(yearDisplay, i.ToString());
ddlYear.Items.Add(li);
setDropDownValue(this.SelectedValue);
private void generateDisplayMessage()
if (this.DisplayMessageLable)
if (this.DisplayControl == DisplayControls.TextBox)
lblMsg.Text = this.DateTimeFormat;
if (this.MinDate != null && this.MinDate.Value != new DateTime())
lblMsg.Text += " From " + this.MinDate.Value.ToString(this.DateTimeFormat);
if (this.MaxDate != null && this.MaxDate.Value != new DateTime())
lblMsg.Text += " To " + this.MaxDate.Value.ToString(this.DateTimeFormat);
private void setDropDownValue(DateTime? dt)
if (ddlDay.Items.Count != 0 && ddlMonth.Items.Count != 0 && ddlYear.Items.Count != 0)
if (dt != null && dt != new DateTime())
ddlDay.SelectedValue = ddlDay.Items.FindByValue(dt.Value.Day.ToString()).Value;
ddlMonth.SelectedValue = ddlMonth.Items.FindByValue(dt.Value.Month.ToString()).Value;
ddlYear.SelectedValue = ddlYear.Items.FindByValue(dt.Value.Year.ToString()).Value;
else
ddlDay.SelectedValue = "0";
ddlMonth.SelectedValue = "0";
ddlYear.SelectedValue = "0";
#endregion
}Usage Of Code in .ascx<cc2:DateTimePicker ID="dtpDOB" DisplayType="Date" DisplayMode="ImageButton" ButtonImage="../Images/calendar.png" runat="server"Changing Value from .cs file dtpDOB.SelectedValue = DateTime.Parse("01/01/2001");It is not reflected in screenHello,
According to your code, it's an ASP.NET user control problem. Please post in
ASP.NET forums where more web developers will give you help.
Thanks for your understanding.
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Problem retrieving javabean instance from request in JSP
I am using WSAD and I created a javabean called confirmBean in default package which contains two private properties fname, lname and public setters and getters
In a servlet I placed values in the bean, then placed the bean in a request and then forwarded to confirm.jsp
confirmBean cb = new confirmBean();
cb.setFname("testing");
req.setAttribute("mybean", cb);
req.getRequestDispatcher("/confirm.jsp").forward(req,res);
Here is my JSP, I used java syntax for retrieving javabean:
<HTML>
<HEAD>
<TITLE>confirm.jsp</TITLE>
</HEAD>
<%@ page
language="java"
contentType="text/html; charset=ISO-8859-1"%>
<%@ page import="confirmBean"%>
<BODY>
<% confirmBean myBean = (confirmBean)request.getAttribute("MYBEAN"); %>
<%= myBean.getFname() %>
</BODY>
</HTML>
and here is the error i am getting when executing:
Error 500: Unable to compile class for JSP c:\testWorkspace\.metadata\.plugins\com.ibm.etools.server.core\tmp0\cache\localhost\server1\Test\TestWeb.war\_confirm.java:3: '.' expected import confirmBean; ^ An error occurred at line: 11 in the jsp file: /confirm.jsp Generated servlet error: c:\testWorkspace\.metadata\.plugins\com.ibm.etools.server.core\tmp0\cache\localhost\server1\Test\TestWeb.war\_confirm.java:78: cannot resolve symbol symbol : class confirmBean location: class org.apache.jsp._confirm confirmBean myBean = (confirmBean)request.getAttribute("MYBEAN"); ^ An error occurred at line: 11 in the jsp file: /confirm.jsp Generated servlet error: c:\testWorkspace\.metadata\.plugins\com.ibm.etools.server.core\tmp0\cache\localhost\server1\Test\TestWeb.war\_confirm.java:78: cannot resolve symbol symbol : class confirmBean location: class org.apache.jsp._confirm confirmBean myBean = (confirmBean)request.getAttribute("MYBEAN"); ^ 3 errors
Please help!!!!1 - Put your bean in a proper package. As of Java1.4 classes in the default package are not visible :
http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=c85f07c1ce8f344d787b7a5146d68:WuuT?bug_id=43615752 - As a matter of style, class names should always start with a capital letter. ie ConfirmBean
3 - Rather than declaring the bean, and retrieving it, from the request manually, have a useBean tag:
<jsp:useBean id="MYBEAN" class="com.mypackage.ConfirmBean" scope="request"/>
of course the id has to be the same as the attribute in scope.
Hope this helps,
evnafets -
Crystal Reports "Report Application Server"
Does anyone have any experience with Crystal Reports' Report Application Server (RAS)?
The provided documentation is very thin and support are taking an age to respond.
I want to use a Bean as a data source for a report. The blurb says you can do this, but the only documented way I can find is for the bean to return a ResultSet, completely missing the point of using a bean or EJB in the first place.
Now, Seagate's sales blurb states that Beans and EJBs can be used as data sources, but if the only way to do this is to return a common or garden ResultSet, what's the point of the bean???
So, has anyone sucessfully used a bean or EJB as a data source for report generation under RAS, or merely CR in general, without resorting to a ResultSet??Crystal Reports YUK!! especially in Java Forum!Tell me about it!!
But, like many developers, I don't get a choice. I have to use CR, and I have to integrate it into a Tomcat (4.1.24) based app. There is a Java API for RAS, but it is a pile of dung. Can you imagine publishing an API with public methods with 'do not use, for internal use only' plastered all over them!!!
But still, back to the original question, I have to find a way of doing this, but Seagate's javadocs are a mess, as are the howto docs. All of the examples, as you might expect, are childishly simple and don't give any insight into the large and hideous API :(
Here is an example of a CR howto.....
There appear to be two ways of creating a data source that isn't an existing report or a database query. This
Runtime data sources
One of the strengths of RAS over the Crystal Reports application, is that the RAS
can use data generated programatically at runtime. With a runtime data source,
you can take data from any source�such as a database, a data stream, or a flat
file�manipulate it with the programming language of your choice, and display it
with RAS.
To use a runtime data source
1 Put your manipulated data in a rowset form that can be processed by the RAS.
Consult the Rowset object and interface in the SDK JavaDocs, for details on
creating rowsets.
2 Create and fill the Dataset object with the rowset data.
3 Create a RowsetController object.
4 Add or set the data source using the RowsetController�s AddDataSource or
SetDataSource methods respectively.
The runtime data source is now available for use.
Note: If you create a report based on a data set, the data that is used is not saved
with the report. To populate the report with data the next time you open it, you
must either re-apply the data source to see current data, or access a saved version
of the data source for preview.
All well and good, but RowsetController doesn't have an AddDataSource or SetDataSource method!!!!
and this......
JavaBean custom data sources
You can use a JavaBean (or a Java class that does not extend the bean type) in order
to specify a custom data source. In order to do this, you will need to:
� Creating a Java class that specifies a custom data source
� Referencing a java class to provide data for a report
Creating a Java class that specifies a custom data source
To use a JavaBean (or a Java class that does not extend the bean type) in order to
specify a custom data source, you will need to create a class that serves as a Java
Beans Connectivity data source for creating Crystal Reports.
This class will need to conforms to the JavaBean standard by defining private
properties that are accessible only through get and set methods. In this way the
Crystal Reports designer can introspect the class as a Bean. The JavaBean
connectivity classes require the following.
� The constructor must have zero parameters.
� Methods that are used as "tables" must have a return type of ResultSet.
� Statement objects must be created using the
ResultSet.TYPE_SCROLL_SENSITIVE and ResultSet.CONCUR_READ_ONLY
arguments.
Note: Methods returning ResultSet can take arguments, these are treated as
Stored Procedure parameters by Crystal Reports.
Now, what the hell is the point of going to the trouble of abstracting your business data into a bean or EJB, if that bean has to return a ResultSet for Crystal Reports to use??!! -
Custom Login using the Pluggable Identity Management Framework
Hi all,
We are trying to establish 2 ways into our application:
1. via a login form
2. seamless login from an external application
To achieve this we are trying to build our own custom authentication using the pluggable IDM framework.
Basically if a secure page is requested, we want to check the header/cookie/request (don't mind which) for a key which is provided by the external application. If present, the key is validated against a web service provided by the external app, the identity is asserted and the user is entered seamlessly into the application. If the header/cookie/request does not contain a key the user is to be redirected to a login page, where they can input username and password which will be validated against our database.
We've created a Token Collector and Token Asserter class, we've modified our custom Login Module to retrieve the identity created by the Token Asserter but we haven't worked out how to get the alternate login page working for users which don't come through the external application.
Has anybody built anything similar? From the documentation it appears we should be able to achieve our goal using the pluggable IDM, but we're going around in circles a bit at the moment.
Any help/sample code would be greatly appreciated.
thanks.Can you tell why the page is not working? I mean, any errors ? What happens when you try to open the protected resource?
Here is an example of the code, I removed some part of the code specific to the bussines so if you have doubts just let me know
token collector
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oracle.security.jazn.collector.CollectorException;
import oracle.security.jazn.collector.TokenCollector;
import oracle.security.jazn.sso.SSOTokenFormatException;
import oracle.security.jazn.token.IdentityToken;
import oracle.security.jazn.token.TokenNotFoundException;
public class MyTokenCollector implements TokenCollector
private Properties _properties;
public void fail(HttpServletRequest request,
HttpServletResponse response, int reason)
throws CollectorException
String loginURL = _properties.getProperty("custom.sso.url.login");
String urlParam = _properties.getProperty("custom.sso.url.param");
String idParam = _properties.getProperty("custom.sso.id.param");
Log.Info("Token collection failed (" + reason + ")");
StringBuffer requestURL = request.getRequestURL();
String queryString = request.getQueryString();
requestURL = requestURL.append("?").append(queryString);
StringBuffer sb = new StringBuffer();
try
sb = sb.append(urlParam).append("=");
String encodedStr =
URLEncoder.encode(requestURL.toString(), "UTF-8");
sb = sb.append(encodedStr);
sb = sb.append("#").append(request.getServerName()).append("#").append(request.getServerPort());
String redirectQueryString = sb.toString();
String rurl = loginURL + "?" + redirectQueryString;
response.sendRedirect(response.encodeRedirectURL(rurl));
catch (UnsupportedEncodingException uee)
SSOTokenFormatException stfe =
new SSOTokenFormatException(uee, 4);
Log.Error(stfe.getMessage());
throw new CollectorException(stfe);
catch (IOException ioe)
Log.Error("IOException occured: " + ioe);
throw new CollectorException(ioe);
public IdentityToken getToken(String tokenType,
HttpServletRequest request,
List tokenNames, Properties properties)
throws TokenNotFoundException, CollectorException
_properties = properties;
String valor = null;
Log.Info("URL: "+request.getRequestURI());
if ( tokenType. equalsIgnoreCase("HTTP_COOKIE"))
valor = procesarCookie(request, tokenNames);
}else if (tokenType.equalsIgnoreCase("HTTP_HEADER"))
valor = procesarHeader(request, tokenNames);
}else
throw new CollectorException("token type not supported");
MyIdentityToken token = new MyIdentityToken(valor);
token.setTokenType(tokenType);
token.setPropiedades(properties);
return token;
private String procesarCookie(HttpServletRequest request, List tokenNames)
throws TokenNotFoundException
if (1 != tokenNames.size())
//Only one cookie can be handled
String error = "Invalid number of cookies check jazn.xml";
throw new TokenNotFoundException(error);
Map cookies = new Hashtable();
Cookie allCookies[] = request.getCookies();
if (allCookies != null)
String cookieName = (String) tokenNames.get(0);
Log.Info( "Searching for cookie: " + cookieName);
Cookie cookie;
for(int i = 0; i < allCookies.length; i++)
cookie = allCookies;
if (cookie.getName().equals(cookieName))
return cookie.getValue();
String error = "Rquired cookie not found";
Log.Error(error);
throw new TokenNotFoundException(error);
}else
String error = "No cookie on request";
throw new TokenNotFoundException(error);
private String procesarHeader(HttpServletRequest request, List tokenNames)
throws TokenNotFoundException
String nombreHeader = (String) tokenNames.get(0);
String header = request.getHeader(nombreHeader);
if (header != null)
return header;
}else
String error = "Request doesn't have the requierd header";
throw new TokenNotFoundException(error);
Token Asserter Example
import java.util.Properties;
import javax.security.auth.Subject;
import oracle.security.jazn.asserter.AsserterException;
import oracle.security.jazn.asserter.TokenAsserter;
import oracle.security.jazn.callback.IdentityCallbackHandler;
import oracle.security.jazn.callback.IdentityCallbackHandlerImpl;
import oracle.security.jazn.token.IdentityToken;
public class MyTokenAsserter
implements TokenAsserter
public void finalize()
throws Throwable
public IdentityCallbackHandler assertIdentity(String tokenType,
IdentityToken token,
Properties properties)
throws AsserterException
InversuraIdentityToken idToken = (InversuraIdentityToken) token;
String valorToken = idToken.getValorToken();
InversuraToken invToken;
try {
invToken = new InversuraToken(valorToken);
if (verificarVigencia(invToken))
IdentityCallbackHandlerImpl idcb = new IdentityCallbackHandlerImpl(invToken.getLogin());
idcb.setAuthenticationType("InversuraSSO");
idcb.setIdentityAsserted(true);
MyPrincipal ppal = new MyPrincipal(invToken.getLogin());
Subject subj = new Subject();
subj.getPrincipals().add(ppal);
idcb.setSubject(subj);
return idcb;
throw new AsserterException("Token expired");
}catch (Exception e)
String error = e.getMessage();
throw new AsserterException(error, e);
public boolean verificarVigencia(InversuraToken token)
return token.estaVigente(); -
I found this class today which is really cool:
http://www.gskinner.com/blog/archives/2007/11/fire_effect_com.html
However, I've never used a public class before. I've been reading up on them all morning. I'll provide the code for it here as well. Anyway, the author also provides a sample application using the class; however, it's a bit different than what I've been reading. He doesn't call the class in his code;however, it seems he has the class in his library, which is news to me.
Anyway, the biggest thing I'm after is trying to design my own application calling this class and just hardcoding the fire aspects in my application. However, I'm coming up empty at every angle. Any help would be much appreciated!
Here's the class he created:
* FireFX by Grant Skinner. May 30, 2007
* Visit www.gskinner.com/blog for documentation, updates and more free code.
* You may distribute and modify this class freely, provided that you leave this header intact,
* and add appropriate headers to indicate your changes. Credit is appreciated in applications
* that use this code, but is not required.
* Please contact [email protected] for more information.
package com.gskinner.effects {
import flash.display.BitmapData;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.ColorTransform;
import flash.filters.ColorMatrixFilter;
import flash.filters.BlurFilter;
import flash.filters.DisplacementMapFilter;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Bitmap;
import flash.display.DisplayObject;
public class FireFX extends Sprite {
private var _fadeRate:Number=0.4;
private var _distortionScale:Number=0.4;
private var _distortion:Number=0.5;
private var _flameHeight:Number=0.3;
private var _flameSpread:Number=0.3;
private var _blueFlame:Boolean = false;
private var _smoke:Number = 0;
// private properties:
// display elements:
private var displayBmp:BitmapData;
private var scratchBmp:BitmapData;
private var perlinBmp:BitmapData;
// geom:
private var mtx:Matrix;
private var pnt:Point;
private var drawColorTransform:ColorTransform;
// filters:
private var fireCMF:ColorMatrixFilter;
private var dispMapF:DisplacementMapFilter;
private var blurF:BlurFilter;
// other:
private var endCount:Number;
private var bmpsValid:Boolean=false;
private var perlinValid:Boolean=false;
private var filtersValid:Boolean=false;
private var _target:DisplayObject;
public function FireFX() {
var frame:DisplayObject = getChildAt(0);
frame.visible = false;
frame.height = height;
frame.width = width;
scaleX = scaleY = 1;
mtx = new Matrix();
pnt = new Point();
startFire();
// getter/setters:
override public function set width(value:Number):void {
bmpsValid &&= (value == width);
super.width = value|0;
override public function get width():Number {
return super.width;
override public function set height(value:Number):void {
bmpsValid &&= (value == height);
super.height = value|0;
override public function get height():Number {
return super.height;
[Inspectable(defaultValue=0.4,name='fadeRate (0-1)')]
* Sets the rate that flames fade as they move up. 0 is slowest, 1 is fastest.
* @default 0.4
public function set fadeRate(value:Number):void {
filtersValid &&= (value == _fadeRate);
_fadeRate = value;
public function get fadeRate():Number {
return _fadeRate;
[Inspectable(defaultValue=0.4,name='distortionScale (0-1)')]
* Sets the scale of flame distortion. 0.1 is tiny and chaotic, 1 is large and smooth.
* @default 0.4
public function set distortionScale(value:Number):void {
perlinValid &&= (value == _distortionScale);
_distortionScale = value;
public function get distortionScale():Number {
return _distortionScale;
[Inspectable(defaultValue=0.4,name='distortion (0-1)')]
* Sets the amount of distortion. 0.1 is little, 1 is chaotic.
* @default 0.4
public function set distortion(value:Number):void {
filtersValid &&= (value == _fadeRate);
_distortion = value;
public function get distortion():Number {
return _distortion;
[Inspectable(defaultValue=0.3,name='flameHeight (0-1)')]
* Sets the how high the flame will burn. 0 is zero gravity, 1 is a bonfire.
* @default 0.3
public function set flameHeight(value:Number):void {
perlinValid &&= (value == _flameHeight);
_flameHeight = value;
public function get flameHeight():Number {
return _flameHeight;
[Inspectable(defaultValue=0.3,name='flameSpread (0-1)')]
* Sets the how much the fire will spread out around the target. 0 is no spread, 1 is a lot.
* @default 0.3
public function set flameSpread(value:Number):void {
filtersValid &&= (value == _flameSpread);
_flameSpread = value;
public function get flameSpread():Number {
return _flameSpread;
[Inspectable(defaultValue=false,name='blueFlame')]
* Indicates whether it should use a blue or red flame.
* @default false
public function set blueFlame(value:Boolean):void {
filtersValid &&= (value == _blueFlame);
_blueFlame = value;
public function get blueFlame():Boolean {
return _blueFlame;
[Inspectable(defaultValue=0,name='smoke (0-1)')]
* Sets the amount of smoke. 0 little, 1 lots.
* @default 0
public function set smoke(value:Number):void {
filtersValid &&= (value == _smoke);
_smoke = value;
public function get smoke():Number {
return _smoke;
[Inspectable(defaultValue='',name='target')]
* Sets the amount of smoke. 0 little, 1 lots.
* @default
public function set targetName(value:String):void {
var targ:DisplayObject = parent.getChildByName(value);
if (targ == null) {
try { targ = parent[value] as DisplayObject; }
catch (e:*) {}
target = targ;
* Defines the shape of the fire. The fire will burn upwards, so it should be near the bottom, and centered in the FireFX component.
* @default
public function set target(value:DisplayObject):void {
_target = value;
clear();
public function get target():DisplayObject {
return _target;
* Clears the fire.
public function clear():void {
if (displayBmp) {
displayBmp.fillRect(displayBmp.rect,0);
* Stops the fire effect after letting it burn down over 20 frames.
public function stopFire():void {
// let the fire burn down for 20 frames:
if (endCount == 0) { endCount = 20; }
private function updateBitmaps():void {
if (displayBmp) {
displayBmp.dispose();
displayBmp = null;
scratchBmp.dispose();
scratchBmp = null;
perlinBmp.dispose();
perlinBmp = null;
displayBmp = new BitmapData(width, height, true, 0);
scratchBmp = displayBmp.clone();
perlinBmp = new BitmapData(width*3, height*3, false, 0);
while (numChildren) { removeChildAt(0); }
addChild(new Bitmap(displayBmp));
updatePerlin();
updateFilters();
bmpsValid = true;
private function updatePerlin():void {
perlinBmp.perlinNoise(30*_distortionScale,20*_distortionScale,1,-Math.random()*1000|0,fals e,true,1|2,false);
perlinBmp.colorTransform(perlinBmp.rect,new ColorTransform(1, 1-_flameHeight*0.5 ,1,1,0,0,0,0));
perlinValid = true;
function updateFilters():void {
if (_blueFlame) {
fireCMF = new ColorMatrixFilter([0.8-0.55*_fadeRate,0,0,0,0,
0,0.93-0.48*_fadeRate,0,0,0,
0,0.1,0.96-0.35*_fadeRate,0,0,
0,0.1,0,1,-25+_smoke*24]);
drawColorTransform = new ColorTransform(0,0,0,1,210,240,255,0);
} else {
fireCMF = new ColorMatrixFilter([0.96-0.35*_fadeRate,0.1,0,0,-1,
0,0.9-0.45*_fadeRate,0,0,0,
0,0,0.8-0.55*_fadeRate,0,0,
0,0.1,0,1,-25+_smoke*24]);
drawColorTransform = new ColorTransform(0,0,0,1,255,255,210,0);
dispMapF = new DisplacementMapFilter(perlinBmp,pnt,1,2,14*_distortion,-30,"clamp");
blurF = new BlurFilter(32*_flameSpread,32*_flameSpread,1);
filtersValid = true;
private function startFire():void {
endCount = 0;
addEventListener(Event.ENTER_FRAME,doFire);
private function doFire(evt:Event):void {
if (_target == null) { return; }
if (!bmpsValid) { updateBitmaps(); }
if (!perlinValid) { updatePerlin(); }
if (!filtersValid) { updateFilters(); }
if (endCount == 0) {
var drawMtx:Matrix = _target.transform.matrix;
drawMtx.tx = _target.x-x;
drawMtx.ty = _target.y-y;
scratchBmp.fillRect(scratchBmp.rect,0);
drawColorTransform.alphaOffset = -Math.random()*200|0;
scratchBmp.draw(_target,drawMtx,drawColorTransform,"add");
scratchBmp.applyFilter(scratchBmp,scratchBmp.rect,pnt,blurF);
displayBmp.draw(scratchBmp,mtx,null,"add");
dispMapF.mapPoint = new Point( -Math.random()*(perlinBmp.width-displayBmp.width)|0, -Math.random()*(perlinBmp.height-displayBmp.height)|0 );
displayBmp.applyFilter(displayBmp,displayBmp.rect,pnt,dispMapF);
displayBmp.applyFilter(displayBmp,displayBmp.rect,pnt,fireCMF);
if (endCount != 0 && --endCount == 0) {
removeEventListener(Event.ENTER_FRAME,doFire);
Then, this is the sample application he gave:
import fl.controls.Slider;
import fl.controls.Label;
import fl.events.SliderEvent;
var params:Array = ["distortion","distortionScale","fadeRate","flameHeight","flameSpread","smoke"]
var l:uint = params.length;
for (var i:uint=0; i<l; i++) {
var label:TextField = new TextField();
label.textColor = 0;
label.text = params[i];
label.width = 140;
label.x = 350;
label.y = 55+50*i;
addChild(label);
label = new TextField();
label.textColor = 0x999999;
label.text = "0.35";
label.name = params[i]+"fld";
label.width = 30;
label.x = 490;
label.y = 55+50*i;
addChild(label);
var slider:Slider = new Slider();
slider.name = params[i];
slider.minimum = -2;
slider.maximum = 2;
slider.addEventListener(SliderEvent.THUMB_DRAG,handleSlider);
addChild(slider);
slider.x = 350;
slider.width = 170;
slider.y = 75+50*i;
slider.snapInterval = 0.05;
slider.value = 0.35;
fireFX[params[i]] = 0.35;
function handleSlider(evt:SliderEvent):void {
fireFX[evt.target.name] = evt.target.value;
(getChildByName(evt.target.name+"fld") as TextField).text = String(evt.target.value);
blueFlame.addEventListener(Event.CHANGE,handleCheckBox);
hideText.addEventListener(Event.CHANGE,handleCheckBox);
function handleCheckBox(evt:Event):void {
fireFX.blueFlame = blueFlame.selected;
obj.visible = !hideText.selected;
Thanks again.Looks like he has fireFX instance on the timeline. Most probably this instances symbol base class is com.gskinner.effects.FireFX
You just need to create a directory structure that reflects his package:
com/gskinner/effects/
where you place his FireFX.as
Or, alternatively, you can remove package path from the class header and place FireFx where all you classes (or your application) are:
package com.gskinner.effects {
to
package {
Then you will just need to instantiate the class. -
JTable size problems due to layout/grid...how can I fix?
This is my code. When the button "Modify Entries" is pressed, it shows a JTable that imports a file called, "entries.data". The items in this file can be read and saved using this program. The problem is that the table is so small when it first opens. How can I set all my buttons to the very bottom of the form and make the table take up more space at the top? It looks to me as if this layout is treating it with the same dimensions as the buttons'.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.util.*;
import java.io.*;
public class CPT extends JPanel implements ActionListener
protected JButton ModifyEntriesButton, ViewEntriesButton, SearchEntriesButton, SaveButton, BackButton;
private final static String newline = "\n";
private DefaultTableModel model;
public CPT ()
super (new GridLayout (10, 0));
model = new PropertiesModel ("entries.data");
ModifyEntriesButton = new JButton ("Modify Entries");
ModifyEntriesButton.setVerticalTextPosition (AbstractButton.TOP);
ModifyEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
ModifyEntriesButton.setToolTipText ("Click this button to modify database entries.");
ModifyEntriesButton.setMnemonic (KeyEvent.VK_M);
ModifyEntriesButton.setActionCommand ("ModifyEntries");
ModifyEntriesButton.addActionListener (this);
ViewEntriesButton = new JButton ("View Entries");
ViewEntriesButton.setVerticalTextPosition (AbstractButton.CENTER);
ViewEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
ViewEntriesButton.setToolTipText ("Click this button to add view all database entries.");
ViewEntriesButton.setMnemonic (KeyEvent.VK_V);
ViewEntriesButton.setActionCommand ("ViewEntries");
ViewEntriesButton.addActionListener (this);
SearchEntriesButton = new JButton ("Search Entries");
SearchEntriesButton.setVerticalTextPosition (AbstractButton.BOTTOM);
SearchEntriesButton.setHorizontalTextPosition (AbstractButton.LEFT);
SearchEntriesButton.setToolTipText ("Click this button to search through all database entries.");
SearchEntriesButton.setMnemonic (KeyEvent.VK_S);
SearchEntriesButton.setActionCommand ("SearchEntries");
SearchEntriesButton.addActionListener (this);
SaveButton = new JButton ("Save");
SaveButton.setVerticalTextPosition (AbstractButton.TOP);
SaveButton.setHorizontalTextPosition (AbstractButton.RIGHT);
SaveButton.setToolTipText ("Click this button to save database entries.");
SaveButton.setMnemonic (KeyEvent.VK_S);
SaveButton.setActionCommand ("Save");
SaveButton.addActionListener (this);
BackButton = new JButton ("Back");
BackButton.setVerticalTextPosition (AbstractButton.BOTTOM);
BackButton.setHorizontalTextPosition (AbstractButton.RIGHT);
BackButton.setToolTipText ("Click this button to return to the main menu.");
BackButton.setMnemonic (KeyEvent.VK_B);
BackButton.setActionCommand ("Back");
BackButton.addActionListener (this);
add (ModifyEntriesButton);
add (ViewEntriesButton);
add (SearchEntriesButton);
class PropertiesModel extends DefaultTableModel
public PropertiesModel (String filename)
addColumn ("Item Number");
addColumn ("Description");
addColumn ("Price");
//Fill model with data from property file
Properties props = readFile (filename);
if (props != null)
Enumeration coll = props.keys ();
while (coll.hasMoreElements ())
String property = (String) coll.nextElement ();
String value = props.getProperty (property, "");
addRow (new Object[]
property, value
private Properties readFile (String filename)
try
Properties props = new Properties ();
props.load (new FileInputStream (filename));
return props;
catch (IOException ioe)
return null;
private boolean saveFile (String filename)
try
Properties props = new Properties ();
for (int i = 0 ; i < model.getRowCount () ; i++)
props.put (model.getValueAt (i, 0), model.getValueAt (i, 1));
props.store (new FileOutputStream (filename), null);
return true;
catch (IOException ioe)
return false;
public void actionPerformed (ActionEvent e)
if ("ModifyEntries".equals (e.getActionCommand ()))
removeAll ();
add (new JScrollPane (new JTable (model)), BorderLayout.CENTER);
add (SaveButton);
add (BackButton);
invalidate ();
updateUI ();
if ("ViewEntries".equals (e.getActionCommand ()))
removeAll ();
add (BackButton);
invalidate ();
updateUI ();
if ("SearchEntries".equals (e.getActionCommand ()))
removeAll ();
add (BackButton);
invalidate ();
updateUI ();
if ("Back".equals (e.getActionCommand ()))
removeAll ();
add (ModifyEntriesButton);
add (ViewEntriesButton);
add (SearchEntriesButton);
invalidate ();
updateUI ();
if ("Save".equals (e.getActionCommand ()))
if (saveFile ("entries.data"))
JOptionPane.showMessageDialog (null, "File saved successfully.");
else
JOptionPane.showMessageDialog (null, "File could not be saved!");
// Create the GUI and show it. For thread safety,
// this method should be invoked from the
// event-dispatching thread.
private static void createAndShowGUI ()
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated (true);
//Create and set up the window.
JFrame frame = new JFrame ("Swisha Computer House");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new CPT ();
newContentPane.setOpaque (true); //content panes must be opaque
frame.setContentPane (newContentPane);
//Display the window.
frame.pack ();
frame.setSize (300, 300);
frame.setVisible (true);
public static void main (String[] args)
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater (new Runnable ()
public void run ()
createAndShowGUI ();
}Hey, and if anyone knows how to get the first column's numbers from the file to show up in descending order (1 through to, say, 500), please let me know.
Thank you for any help.It looks to me as if this layout is treating it with the same dimensions as the buttons'.Thats the way a GridLayout works.
Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers. You can mix an match individual Layout Managers to get the effect desired.
I would suggest you need to change your design. Your code for continually removing and adding components is not the best design. You should probably have a panel with all your buttons. Then you would have different panels for each of your sub functions. The display of these panels would be controlled by a Card Layout. The tutorial has working examples of this.
You can't use a Properties file to save data from the table (at least not the way you are attempting to use it). I gave you a solution in your last posting. -
Problem with code: reading a string
Hi,
I am very new to java so excuse my naivety. i need to write some code which will decode an encrypted message. the message is stored as a string which is a series of integers which. Eg. Nick in this code is 1409030110 where a = 1, b = 2,... and there is a 0 (zero) after every word. at the moment the code only goes as far as seperating the individual characters in the message up and printing them out onscreen.
Heres the code:
int index = 0;
while(index < line.length() - 1) {
char first = line.charAt(index);
char second = line.charAt(index + 1);
if(second == 0) {
char third = line.charAt(index + 2);
if(third == 0) {
System.out.print(first + "" + second);
index = index + 3;
else {
System.out.print(first);
index = index + 2;
else {
System.out.print(first + "" + second);
index = index + 3;
Basically its meant to undo the code by reading the first two characters in the string then determining whether the second is equal to 0 (zero). if the second is 0 then it needs to decide whether the third character is 0 (zero) because the code could be displaying 10 or 20. if so the first two characters are recorded to another string and if not only the first is recorded. obviously if the second character is not a zero then the code will automatically record the first 2 characters.
my problem is that the code doesnt seem to recognise the 0 (zero) values. when i run it thru with the string being the coded version of Nick above (1409030110) the outputted answer is 1490010 when it should be 149311. as far as i can see the code is right but its not working! basically the zeros are begin removed but i need each group of non-zero digits to be removed seperately so i can decode them.
if anyone has understood any of this could you give me some advice, im at my wits end!
Thanks, NickTry something like this:
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
public class SimpleDecoder
/** Default mapping file */
public static final String DEFAULT_MAPPING_FILE = "SimpleDecoder.properties";
/** Regular expression pattern to match one or more zeroes */
public static final String SEPARATOR = "0+";
private Properties decodeMapping = new Properties();
public static void main(String [] args)
try
SimpleDecoder decoder = new SimpleDecoder();
decoder.setDecodeMapping(new FileInputStream(DEFAULT_MAPPING_FILE));
for (int i = 0; i < args.length; ++i)
System.out.println("Original encoded string: " + args);
System.out.println("Decoded string : " + decoder.decode(args[i]));
catch (Exception e)
e.printStackTrace();
public void setDecodeMapping(InputStream stream) throws IOException
this.decodeMapping.load(stream);
public String decode(final String encodedString)
StringBuffer value = new StringBuffer();
String [] tokens = encodedString.split(SEPARATOR);
for (int i = 0; i < tokens.length; ++i)
value.append(this.decodeMapping.getProperty(tokens[i]));
return value.toString();
I gave your "1409030110" string on the command line and got back "nick". The SimpleDecoder.properties file had 26 lines in it:
1 = a
2 = b
3 = c
// etc;Not a very tricky encryption scheme, but it's what you asked for. - MOD -
Nice solution to change a lot of procedures at once.
if you have to do little changes in a lot of your Procedures / Functions or Packages here is a nice solution to do this in a very short time:
CREATE TABLE T_SOURCE
SOURCE_ID NUMBER,
NAME VARCHAR2(30 BYTE),
SOURCETEXT CLOB
CREATE OR REPLACE PROCEDURE CIAS_PUFFER.pr_t_source
IS
NAME: pr_t_source
$Archive: //PVCS/archives/10gh/PR_T_SOURCE.prc_v $
$Author: ext0523 $
$Date: Aug 04 2008 17:26:54 $
$Revision: 1.2 $
CURSOR c_all_obj
IS
SELECT object_name
FROM all_objects
WHERE owner <>'SYS'
AND object_type = 'PROCEDURE'
ORDER BY object_name;
CURSOR c_prog (cp_name VARCHAR2)
IS
SELECT *
FROM all_source
WHERE NAME = cp_name
ORDER BY line;
v_replace VARCHAR2 (999);
v_st CLOB;
i PLS_INTEGER := 0;
BEGIN
EXECUTE IMMEDIATE ('truncate table t_source');
FOR rec_all_obj IN c_all_obj
LOOP
i := i + 1;
v_st := '--$ARCHIVE$'||chr(10)||'--$AUTHOR$'||chr(10)||'--$DATE$'
||chr(10)||'--$REVISION$'||chr(10)||chr(10);
v_st := v_st||'CREATE OR REPLACE ';
FOR rec_prog IN c_prog (rec_all_obj.object_name)
LOOP
v_replace := UPPER (rec_prog.text);
if instr(v_replace,'$ARCHIVE') >0 then v_replace :=''; end if;
if instr(v_replace,'$AUTHOR') >0 then v_replace :=''; end if;
if instr(v_replace,'$DATE') >0 then v_replace :=''; end if;
if instr(v_replace,'$REVISION') >0 then v_replace :=''; end if;
v_replace :=
REPLACE (v_replace,
'[email protected]',
'prot_easy_cias'
v_replace :=
REPLACE (v_replace, '[email protected]', 'easy2cias');
v_st := v_st || v_replace;
END LOOP;
INSERT INTO t_source
VALUES (i, rec_all_obj.object_name, v_st);
END LOOP;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
NULL;
WHEN OTHERS
THEN
-- Consider logging the error and then re-raise
RAISE;
END pr_t_source;
// classpath= /ORACLE/u01/app/oracle/product/10.2.0.3/jdbc/lib/ojdbc14.jar
// Java SQL classes
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
// Oracle JDBC driver class
import oracle.jdbc.OracleDriver;
// Java IO classes
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
//Java Util classes
import java.util.Properties;
* This class demonstrates the Oracle JDBC 10g enhanced features for inserting
* and retrieving CLOB data from the database. Using the new features, large
* data of more than 32765 bytes can be inserted into the database using the
* existing PreparedStatement.setString() and PreparedStatement.getString()
* methods.
public class ClobMan {
/* Database Connection object */
private Connection conn = null;
/* Variables to hold database details */
private String url = null;
private String user = null;
private String password = null;
// Create a property object to hold the username, password and
// the new property SetBigStringTryClob.
private Properties props = new Properties();
/* String to hold file name */
private String fileName = null;
* Default Constructor to instantiate and get a handle to class methods
* and variables.
public ClobMan(String fileName) {
this.fileName = fileName;
* Main runnable class.
public static void main(String[] args) throws SQLException {
// Instantiate the main class.
ClobMan clobMan = new ClobMan(args[0]);
// Load the Oracle JDBC driver class.
DriverManager.registerDriver(new OracleDriver());
// Load the database details into the variables.
String dbUrl = "jdbc:oracle:thin:@pmol:1550:dbpmol";
clobMan.url = dbUrl;
clobMan.user = "gh10";
clobMan.password = "secret";
// Populate the property object to hold the username, password and
// the new property 'SetBigStringTryClob' which is set to true. Setting
// this property allows inserting of large data using the existing
// setString() method, to a CLOB column in the database.
clobMan.props.put("user", clobMan.user );
clobMan.props.put("password", clobMan.password);
clobMan.props.put("SetBigStringTryClob", "true");
// Check if the table 'CLOB_TAB' is present in the database.
//clobMan.checkTables();
// Call the methods to insert and select CLOB from the database.
//clobMan.insertClob();
clobMan.selectClob();
* This method will insert the data into a CLOB column in the database.
* Oracle JDBC 10g has enhanced the existing PreparedStatement.setString()
* method for setting the data more than 32765 bytes. So, using setString(),
* it is now easy to insert CLOB data into the database directly.
private void insertClob() throws SQLException {
// Create a PreparedStatement object.
PreparedStatement pstmt = null;
try {
// Create the database connection, if it is closed.
if ((conn==null)||conn.isClosed()){
// Connect to the database.
conn = DriverManager.getConnection( this.url, this.props );
// Create SQL query to insert data into the CLOB column in the database.
String sql = "INSERT INTO clob_tab VALUES(?)";
// Read a big file(larger than 32765 bytes)
String str = this.readFile();
// Create the OraclePreparedStatement object
pstmt = conn.prepareStatement(sql);
// Use the same setString() method which is enhanced to insert
// the CLOB data. The string data is automatically transformed into a
// clob and inserted into the database column. Make sure that the
// Connection property - 'SetBigStringTryClob' is set to true for
// the insert to happen.
pstmt.setString(1,str);
// Execute the PreparedStatement
pstmt.executeUpdate();
} catch (SQLException sqlex) {
// Catch Exceptions and display messages accordingly.
System.out.println("SQLException while connecting and inserting into " +
"the database table: " + sqlex.toString());
} catch (Exception ex) {
System.out.println("Exception while connecting and inserting into the" +
" database table: " + ex.toString());
} finally {
// Close the Statement and the connection objects.
if (pstmt!=null) pstmt.close();
if (conn!=null) conn.close();
* This method reads the CLOB data from the database by using getString()
* method.
private void selectClob() throws SQLException {
// Create a PreparedStatement object
PreparedStatement pstmt = null;
// Create a ResultSet to hold the records retrieved.
ResultSet rset = null;
try {
// Create the database connection, if it is closed.
if ((conn==null)||conn.isClosed()){
// Connect to the database.
conn = DriverManager.getConnection( this.url, this.props );
// Create SQL query statement to retrieve records having CLOB data from
// the database.
String sqlCall = "SELECT rownum, name, sourcetext FROM t_source";
pstmt= conn.prepareStatement(sqlCall);
// Execute the PrepareStatement
rset = pstmt.executeQuery();
String rownum = null;
String o_name =null;
String clobVal = null;
// Get the CLOB value from the resultset
//java.io.BufferedWriter out = new java.io.BufferedWriter(new java.io.FileWriter("pr_all.sql"));
while (rset.next()) {
rownum = rset.getString(1);
o_name = rset.getString(2);
clobVal = rset.getString(3);
System.out.println(" length: "+clobVal.length()+" "+o_name+" "+rownum);
java.io.BufferedWriter out =
new java.io.BufferedWriter(new java.io.FileWriter(o_name+".prc"));
out.write(clobVal);
out.newLine();
out.write("/");
out.newLine();
out.newLine();
out.flush();
out.close();
} catch (SQLException sqlex) {
// Catch Exceptions and display messages accordingly.
System.out.println("SQLException while connecting and querying the " +
"database table: " + sqlex.toString());
} catch (Exception ex) {
System.out.println("Exception while connecting and querying the " +
"database table: " + ex.toString());
} finally {
// Close the resultset, statement and the connection objects.
if (rset !=null) rset.close();
if (pstmt!=null) pstmt.close();
if (conn!=null) conn.close();
* Method to check if the table ('CLOB_TAB') exists in the database; if not
* then it is created.
* Table Name: CLOB_TAB
* Column Name Type
* col_col CLOB
private void checkTables() {
Statement stmt = null;
ResultSet rset = null;
try {
// Create the database connection, if it is closed.
if ((conn==null)||conn.isClosed()){
// Connect to the database.
conn = DriverManager.getConnection( this.url, this.props );
// Create Statement object
stmt = conn.createStatement();
// Check if the table is present
rset = stmt.executeQuery(" SELECT table_name FROM user_tables "+
" WHERE table_name = 'CLOB_TAB' ");
// If the table is not present, then create the table.
if (!rset.next()) {
// Table does not exist, create it
stmt.executeUpdate(" CREATE TABLE clob_tab(clob_col CLOB)");
} catch (SQLException sqlEx) {
System.out.println("Could not create table clob_tab : "
+sqlEx.toString());
} finally {
try {
if( rset != null ) rset.close();
if( stmt != null ) stmt.close();
if (conn!=null) conn.close();
} catch(SQLException ex) {
System.out.println("Could not close objects in checkTables method : "
+ex.toString());
* This method reads the specified text file and, returns the content
* as a string.
private String readFile()
throws FileNotFoundException, IOException{
// Read the file whose content has to be passed as String
BufferedReader br = new BufferedReader(new FileReader(fileName));
String nextLine = "";
StringBuffer sb = new StringBuffer();
while ((nextLine = br.readLine()) != null) {
sb.append(nextLine);
// Convert the content into to a string
String clobData = sb.toString();
// Return the data.
return clobData;
sqlplus -s @pr_all.sql;Is there a better way to satisfy such claim?I have to say I would not consider doing this in the database. Source control would allow you to manage (review / commit, not to mention revert) the results of such a potentially dangerours global search and replace.
Such as if it UPPERcased all my source code for example.
v_replace := UPPER (rec_prog.text);
Maybe you are looking for
-
Mail keeps asking for password and icloud setting do not load in system preferences
Hi, I have a mac mini server with mavericks, i have 2 iMacs as clients running mavericks too, when i use iMac (A) mail app and icloud work fine, them i take iMac (B) and mail app start asking for password , it just won't take the password, icloud do
-
Here my sample design of the bulk process with limit of row inserted declare n_rows_to_process NUMBER := 1000; CURSOR my_cursor IS select XXXXX BEGIN OPEN my_cursor; loop FETCH my_cursor BULK COLLECT INTO XXXX LIMIT n_rows_to_process FORALL i IN 1 ..
-
hi can any one provide me the Business process template for SAP BI/BO Requirements gauthering? any helpful links? Edited by: Srikanth.T on Oct 27, 2011 10:39 AM
-
Is there a way to view search results in column view?
-
Selected TAG doesn't format text.
After pressing Enter key (PC) to begin new paragraph, then selecting TAG for that paragraph (eg., Heading2Body), text stays unformatted. Pressing Apply several times makes no difference. To solve this problem, I did a Copy Special < Copy Paragraph Fo