Search Results

Search found 308 results on 13 pages for 'the prop'.

Page 6/13 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • C# Reflection StackTrace get value

    - by John
    I'm making pretty heavy use of reflection in my current project to greatly simplify communication between my controllers and the wcf services. What I want to do now is to obtain a value from the Session within an object that has no direct access to HttpSessionStateBase (IE: Not a controller). For example, a ViewModel. I could pass it in or pass a reference to it etc. but that is not optimal in my situation. Since everything comes from a Controller at some point in my scenario I can do the following to walk the sack to the controller where the call originated, pretty simple stuff: var trace = new System.Diagnostics.StackTrace(); foreach (var frame in trace.GetFrames()) { var type = frame.GetMethod().DeclaringType; var prop = type.GetProperty("Session"); if(prop != null) { // not sure about this part... var value = prop.GetValue(type, null); break; } } The trouble here is that I can't seem to work out how to get the "instance" of the controller or the Session property so that I can read from it.

    Read the article

  • How do I assert that two arbitrary type objects are equivalent, without requiring them to be equal?

    - by Tomas Lycken
    To accomplish this (but failing to do so) I'm reflecting over properties of an expected and actual object and making sure their values are equal. This works as expected as long as their properties are single objects, i.e. not lists, arrays, IEnumerable... If the property is a list of some sort, the test fails (on the Assert.AreEqual(...) inside the for loop). public void WithCorrectModel<TModelType>(TModelType expected, string error = "") where TModelType : class { var actual = _result.ViewData.Model as TModelType; Assert.IsNotNull(actual, error); Assert.IsInstanceOfType(actual, typeof(TModelType), error); foreach (var prop in typeof(TModelType).GetProperties()) { Assert.AreEqual(prop.GetValue(expected, null), prop.GetValue(actual, null), error); } } If dealing with a list property, I would get the expected results if I instead used CollectionAssert.AreEquivalent(...) but that requires me to cast to ICollection, which in turn requries me to know the type listed, which I don't (want to). It also requires me to know which properties are list types, which I don't know how to. So, how should I assert that two objects of an arbitrary type are equivalent? Note: I specifically don't want to require them to be equal, since one comes from my tested object and one is built in my test class to have something to compare with.

    Read the article

  • Setting objct literal property value via asynchronous callback.

    - by typeof
    I'm creating a self-contained javascript utility object that detects advanced browser features. Ideally, my object would look something like this: Support = { borderRadius : false, // values returned by functions gradient : false, // i am defining dataURI : true }; My current problem deals with some code I'm adapting from Weston Ruter's site which detects dataURI support. It attempts to use javascript to create an image with a dataURI source, and uses onload/onerror callbacks to check the width/height. Since onload is asynchronous, I lose my scope and returning true/false does not assign true/false to my object. Here is my attempt: Support = { ... dataURI : function(prop) { prop = prop; // keeps in closure for callback var data = new Image(); data.onload = data.onerror = function(){ if(this.width != 1 || this.height != 1) { that = false; } that = true; } data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; return -1; }(this) }; I'm executing the anonymous function immediately, passing this (which I hoped was a reference to Support.dataURI), but unfortunately references the window object -- so the value is always -1. I can get it to work by using an externally defined function to assign the value after the Support object is created... but I don't think it's very clean that way. Is there a way for it to be self-contained? Can the object literal's function reference the property it's assigned to?

    Read the article

  • Jquery Mobile 1.2 Multiple Checkbox Selection Issue

    - by user1819957
    I'm coding a Jquery Mobile 1.2, Jquery 1.8.2, css, and HTML 5 based app that I need to allow the user to select multiple images and execute a command. The following works if I do NOT use the jquery.mobile-1.2.0.min.js library: CSS Code: .image-checkbox-container input[type="checkbox"]{ display: none; } .image-checkbox-container img{ border: 0; margin: 4px; } HTML: JQuery: $('.image-checkbox-container img').live('click', function(){ if(!$(this).prev('input[type="checkbox"]').prop("checked")){ $(this).prev('input[type="checkbox"]').prop("checked", true); this.style.border = '4px solid #38A'; this.style.margin = '0px'; }else{ $(this).prev('input[type="checkbox"]').prop("checked", false); this.style.border = '0'; this.style.margin = '4px'; } }); As soon as I add in the jquery.mobile-1.2.0.min.js library to the code it does not function correctly anymore. The unchecking/unselecting of the checkboxes does not work. I attempted to use the checkboxradio("refresh") but did not have any luck. Any suggestions would be much appreciated. Thanks

    Read the article

  • C# Reflection StackTrack get value

    - by John
    I'm making pretty heavy use of reflection in my current project to greatly simplify communication between my controllers and the wcf services. What I want to do now is to obtain a value from the Session within an object that has no direct access to HttpSessionStateBase (IE: Not a controller). For example, a ViewModel. I could pass it in or pass a reference to it etc. but that is not optimal in my situation. Since everything comes from a Controller at some point in my scenario I can do the following to walk the sack to the controller where the call originated, pretty simple stuff: var trace = new System.Diagnostics.StackTrace(); foreach (var frame in trace.GetFrames()) { var type = frame.GetMethod().DeclaringType; var prop = type.GetProperty("Session"); if(prop != null) { // not sure about this part... var value = prop.GetValue(type, null); break; } } The trouble here is that I can't seem to work out how to get the "instance" of the controller or the Session property so that I can read from it.

    Read the article

  • How to refactor jquery

    - by Pierce McGeough
    I have buttons on the page that will activate and deactive settings. the Ids are the same bar their prefix e.g I have '#rl-activate', '#rl-deactivate', '#cl-activate', '#cl-deactivate' Is there a way to refactor this code so i am not doing it for every button on the page. // rl activate $('#rl-activate').click(function(){ $('#rl-activate').hide(); $('#rl-deactivate').show(); $('#rl').val(50).prop('selected', true); $('#rl').prop('disabled', false).trigger('liszt:updated'); displayCPM(); newPrice(); checkSettings(); }); // rl deactivate $('#rl-deactivate').click(function(){ $('#rl-deactivate').hide(); $('#rl-activate').show(); $('#rl').prop('disabled', true).trigger('liszt:updated'); $('#rl').val('').trigger('liszt:updated'); displayCPM(); newPrice(); checkSettings(); }); So for the next one all that changes will be the rl to cl to bm etc

    Read the article

  • How to create a text file from column and FTP that text file to server

    - by addi
    I have workbook with 2 sheets (Sheet1 and sheet2). On sheet1 user will enter the data which will be populated in the column B and then column C will hold the values from Col A and B on sheet2. I need to create a text file from the values in coloumn C on a click of a button and then upload(FTP) that file to a server. So the sheet1 will have 2 buttons. Button1 will save the excel file and create the text file in windows temp directory. e.g text.xls text.prop (text file whoch has all the values in column C on sheet2) Button2 will upload (FTP) the text file (.prop) to a server. Can anyone please send me the steps and VB code to achieve the above tasks? Thanks in Advance Addi

    Read the article

  • Touchpad not working after login in Ubuntu

    - by Maria Mateescu
    At some point my touchpad stopped working on Lenovo x220 under Ubuntu 11.10, after login. I have found two possible solutions for that online, but neither of them work. First, gconftool-2 --set --type boolean /desktop/gnome/peripherals/touchpad/touchpad_enabled true and a second one, xinput set-int-prop "SynPS/2 Synaptics TouchPad" "Synaptics Off" 8 0 After looking more carefully into xinput I have realized that xinput list-props "SynPS/2 Synaptics TouchPad" outputs: Device Enabled (132): 0 This field seems to be stuck to zero, because trying to set it back to 1 by: xinput set-int-prop "SynPS/2 Synaptics TouchPad" "Device Enabled" 8 1 doesn't seem to have any effect, e.g. I still have: Device Enabled (132): 0 Any ideas? Thank you!

    Read the article

  • Lenovo Ideapad 205 and Ubuntu 12.04 LTS

    - by Oranges
    I just wanted to report one thing, because I know there are a lot of Ideapad S205 users out there, that had issues running Ubuntu on their Lenovo Ideapad S205 in the past. Lenovo Ideapad with Ubuntu 12.04 LTS: Everything works out of the box. I just installed it and everything, including the microphone, the webcam, the WLAN, the AMD E-350 CPU/GPU and the sound worked right away. In other words: Everything works. Even the AMD E-350 GPU works very well with the Open Source drivers and with the prop. drivers. The prop. drivers were automatically offered to me via Ubuntu itself. It works great. A long idea, written short: I love it. It's extremly stable and very fast. I am using the German version of the Idepad S205, combined with the 32bit version of Ubuntu. There is only one, single thing to keep in mind when installing Ubuntu on the S205: Plugin your USB/CD/DVD drive in the left USB-Port. I don't know why, but it only works with the USB-Port on the left side of the Netbook. This is only for installing Ubuntu. After it has been installed and updated successfully, all of the USB ports will work. Oranges - feedback on Lenovo S205 with Ubuntu 12.04 LTS.

    Read the article

  • Spring / Hibernate / JUnit - No Hibernate Session bound to Thread

    - by Marty Pitt
    Hi I'm trying to access the current hibernate session in a test case, and getting the following error: org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63) at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:574) I've clearly missed some sort of setup, but not sure what. Any help would be greatly appreciated. This is my first crack at Hibernate / Spring etc, and the learning curve is certainly steep! Regards Marty Code follows: The offending class: public class DbUnitUtil extends BaseDALTest { @Test public void exportDtd() throws Exception { Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); Connection hsqldbConnection = session.connection(); IDatabaseConnection connection = new DatabaseConnection(hsqldbConnection); // write DTD file FlatDtdDataSet.write(connection.createDataSet(), new FileOutputStream("test.dtd")); } } Base class: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class BaseDALTest extends AbstractJUnit4SpringContextTests { public BaseDALTest() { super(); } @Resource protected SessionFactory sessionFactory; } applicationContext.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>org.hsqldb.jdbcDriver</value> </property> <property name="url"> <value>jdbc:hsqldb:mem:sample</value> </property> <property name="username"> <value>sa</value> </property> <property name="password"> <value></value> </property> </bean> <bean id="sessionFactory" class="com.foo.spring.AutoAnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="entityPackages"> <list> <value>com.sample.model</value> </list> </property> <property name="schemaUpdate"> <value>true</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> </beans>

    Read the article

  • How can I bind a custom color to WPF toolkit ColorPicker? [on hold]

    - by tube-builder
    I need to bind the SelectedColor property of ColorPicker to a custom color which is not present in available colors. I created a simple test to show my problem. My xaml: <xctk:ColorPicker SelectedColor="{Binding Path=Test}"></xctk:ColorPicker> Code behind (CurrentStyle.PenColor returns an integer value which equals 13109765): public Color Test { get; set; } public MyClass() { DataContext = this; Test = Color.FromArgb((byte)((CurrentStyle.PenColor >> 24) & 0xFF), (byte)((CurrentStyle.PenColor >> 16) & 0xFF), (byte)((CurrentStyle.PenColor >> 8) & 0xFF), (byte)(CurrentStyle.PenColor & 0xFF)); InitializeComponent(); } And that's how my ColorPicker looks like when the window is loaded (I don't have enough rep to post images so it's just links): http://s22.postimg.org/frzh2fgy9/image.png Though, when I go to Advanced colors I can see that the color has been recognized and set correctly. Here is a pic: http://s13.postimg.org/gjv4cmy07/image.png Hope for your help. Thanks a lot! EDIT I implemented INotifyPropertyChanged, still to no avail. Here's the code: public Color Test { get { return test; } set { if (test != value) { test = value; OnPropertyChanged("Test"); } } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string prop) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(prop)); } Maybe I'm doing smth wrong here.

    Read the article

  • Compiz slow under proprietary nvidia driver

    - by gsedej
    Hi! I am using Ubuntu 10.10 and have problem with proprietary nvidia driver for my GeForce GTS 250. I have issue with poor Compiz performance. And there is also open-source "noueau" driver. Proprietary: I tried many versions but neither works fast on desktop. This means 30 FPS without heavy effects. Currently I am using version 270.18. Even normal desktop use feels bad (moving windows) In games (and 3D benchmark) it is really good! (Unigine Heaven works good!) Open-source "nouveau": Very fast on desktop with heavy effects (blur, ...). I have 300 FPS and more, even in Expo mode. Games were good but not as good as prop. And driver causes xorg to crash even the latest (ppa:xorg-edgers/nouveau), so I switched back to proprietary. I also have computer with Ubuntu 10.04, GeForce 8600GT and drivers around 185.x and Compiz works great there. There is similar question Nvidia proprietary driver performance in 10.10 Which version of nvidia (prop) driver is fast in Compiz in Ubuntu 10.10? How do you install a specific version of nvidia driver? Is it the case that each newer driver works slower on compiz?

    Read the article

  • Why are transactions not rolling back when using SpringJUnit4ClassRunner/MySQL/Spring/Hibernate

    - by Trevor
    I am doing unit testing and I expect that all data committed to the MySQL database will be rolled back... but this isn't the case. The data is being committed, even though my log was showing that the rollback was happening. I've been wrestling with this for a couple days so my setup has changed quite a bit, here's my current setup. LoginDAOTest.java: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"file:web/WEB-INF/applicationContext-test.xml", "file:web/WEB-INF/dispatcher-servlet-test.xml"}) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) public class UserServiceTest { private UserService userService; @Test public void should_return_true_when_user_is_logged_in () throws Exception { String[] usernames = {"a","b","c","d"}; for (String username : usernames) { userService.logUserIn(username); assertThat(userService.isUserLoggedIn(username), is(equalTo(true))); } } ApplicationContext-Text.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="Ecosim07"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="userService" class="Service.UserService"> <property name="userDAO" ref="userDAO"/> </bean> <bean id="userDAO" class="DAO.UserDAO"> <property name="hibernateTemplate" ref="hibernateTemplate"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mappingResources"> <list> <value>/himapping/User.hbm.xml</value> <value>/himapping/setup.hbm.xml</value> <value>/himapping/UserHistory.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory"/> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> </beans> I have been reading about the issue, and I've already checked to ensure that the MySQL database tables are setup to use InnoDB. Also I have been able to successfully implement rolling back of transactions outside of my testing suite. So this must be some sort of incorrect setup on my part. Any help would be greatly appreciated :)

    Read the article

  • java.sql.SQLException: No suitable driver found for jdbc:db2:

    - by Celia
    Im using hibernate to connect to my DB2 database. I got java.sql.SQLException: No suitable driver found for jdbc:db2://ldild4268.mycompany.com:55000/myDB. I have db2jcc.jar, db2jcc_javax.jar, db2jcc_license_cu.jar, db2policy.jar, db2ggjava.jar and db2umplugin.jar added into my Java Build Path. I am able to connect to my database through SQuirrel. database.properties: jdbc.driverClassName=com.ibm.db2.jcc.DB2Driver jdbc.url=jdbc:db2://ldild4268.mycompany.com:55000/myDB jdbc.username=uname jdbc.password=pwd datasource.xml: <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>/WEB-INF/database.properties</value> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> hibernate.xml: <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.DB2Dialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="mappingResources"> <list> <value>/myModel.hbm.xml</value> </list> </property> </bean> myModel.hbm.xml: <hibernate-mapping> <class name="com.myCompany.model.myModel" table="table1" catalog=""> <composite-id> <key-property name="key1" column="key1" length="10"/> <key-property name="key2" column="key2" length="19"/> </composite-id> <property name="name" type="string"> <column name="Name" length="50"/> </property> </class> </hibernate-mapping> myModelDaoImpl: @Repository("myModelDao") public class myModelDaoImpl extends PortfolioHibernateDaoSupport implements myModelDao{ private SessionFactory sessionFactory; public List<Date> getKey1() { return this.sessionFactory.getCurrentSession() .createQuery("select pn.key1 from com.myCompany.model.myModel pn") .list(); } public String getPs() { String query = "select pn.name from com.myCompany.model.myModel pn where pn.key1='2011-09-30' and pn.key2=1049764"; List list = getHibernateTemplate().find(query); } } also, the method getKey1 throws nullPointer exception. How can I use createquery instead of hibernateTemplate? Thanks in advance!

    Read the article

  • Unable to execute native sql query

    - by Renjith
    I am developing an application with Spring and hibernate. In the DAO class, I was trying to execute a native sql as follows: SELECT * FROM product ORDER BY unitprice ASC LIMIT 6 OFFSET 0 But the system throws an exception. org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63) org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:544) com.dao.ProductDAO.listProducts(ProductDAO.java:15) com.dataobjects.impl.ProductDoImpl.listProducts(ProductDoImpl.java:26) com.action.ProductAction.showProducts(ProductAction.java:53) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) application-context.xml is show below <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> <!-- Hibernate SessionFactory --> <!-- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"--> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource"/> </property> <property name="configLocation"> <value>WEB-INF/classes/hibernate.cfg.xml</value> </property> <property name="configurationClass"> <value>org.hibernate.cfg.AnnotationConfiguration</value> </property> <!-- <property name="annotatedClasses"> <list> <value>com.pojo.Product</value> <value>com.pojo.User</value> <value>com.pojo.UserLogin</value> </list> </property> --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <!-- User Bean definitions --> <bean name="/logincheck" class="com.action.LoginAction"> <property name="userDo" ref="userDo" /> </bean> <bean id="userDo" class="com.dataobjects.impl.UserDoImpl" > <property name="userDAO" ref="userDAO" /> </bean> <bean id="userDAO" class="com.dao.UserDAO" > <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean name="/listproducts" class="com.action.ProductAction"> <property name="productDo" ref="productDo" /> </bean> <bean id="productDo" class="com.dataobjects.impl.ProductDoImpl" > <property name="productDAO" ref="productDAO" /> </bean> <bean id="productDAO" class="com.dao.ProductDAO" > <property name="sessionFactory" ref="sessionFactory" /> </bean> And DAO class is public class ProductDAO extends HibernateDaoSupport{ public List listProducts(int startIndex, int incrementor) { org.hibernate.Session session = getHibernateTemplate().getSessionFactory().getCurrentSession(); String queryString = "SELECT * FROM product ORDER BY unitprice ASC LIMIT 6 OFFSET 0"; List list = null; try{ session.beginTransaction(); org.hibernate.Query query = session.createQuery(queryString); list = query.list(); session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); } finally { session.close(); } return list; } public List getProductCount() { String queryString = "SELECT COUNT(*) FROM Product"; return getHibernateTemplate().find(queryString); } } Any thoughts to fix it up?

    Read the article

  • error initializing multiple configuration files

    - by lurscher
    Hi, during initialization startup on tomcat, the configurations are: 1) a webapp/WEB-INF/web.xml that imports yummy-servlet.xml in contextConfigLocation (although i'm aware that is not required since the servlet-name is yummy it will try to load yummy-servlet.xml by default) 2) a webapp/WEB-INF/yummy-servlet.xml that imports a spring/applicationContext-hibernate.xml file 3) a webapp/WEB-INF/spring/applicationContext-hibernate.xml that imports a applicationContext-dataSource.xml file 4) a webapp/WEB-INF/spring/applicationContext-dataSource.xml i'm getting errors about Failed to import bean definitions from relative location, but the stack trace is not very explicit about exactly what is the problem, i've been looking at these since yesterday and i really don't see any problem on the files my web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>hello-spring3-RC1</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/yummy-servlet.xml</param-value> </context-param> <!-- <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/applicationContext-hibernate.xml</param-value> </context-param> --> <!-- Location of the Log4J config file, for initialization and refresh checks. Applied by Log4jConfigListener. --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>yummy</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>yummy</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> my yummy-servlet.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <import resource="spring/applicationContext-hibernate.xml"/> <context:component-scan base-package="com.mine.web.controllers"/> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans> my applicationContext-hibernate.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- import the dataSource definition --> <import resource="applicationContext-dataSource.xml"/> <!-- Configurer that replaces ${...} placeholders with values from a properties file --> <!-- (in this case, Hibernate-related settings for the sessionFactory definition below) --> <context:property-placeholder location="classpath:jdbc.properties"/> <context:property-placeholder location="classpath:hibernate.properties"/> <!-- Hibernate SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingResources="hello.hbm.xml"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop> </props> </property> <property name="eventListeners"> <map> <entry key="merge"> <bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/> </entry> </map> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory"/> <!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= --> <!-- Activates various annotations to be detected in bean classes: Spring's @Required and @Autowired, as well as JSR 250's @Resource. --> <context:annotation-config/> <!-- Instruct Spring to perform declarative transaction management automatically on annotated classes. --> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="EntityManager" class="com.mine.persistence.hibernate.HibernateHelloWorldDao"/> </beans> and my applicationContext-dataSource.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"> <!-- Configurer that replaces ${...} placeholders with values from a properties file --> <!-- (in this case, JDBC-related settings for the dataSource definition below) --> <context:property-placeholder location="classpath:jdbc.properties"/> <context:property-placeholder location="classpath:hibernate.properties"/> <!-- data source using apache common dbcp pool manager <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}"/>--> <!-- c3p0 pool manager data source --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClassName}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="initialPoolSize" value="${hibernate.c3p0.min_size}"/> <property name="minPoolSize" value="${hibernate.c3p0.min_size}"/> <property name="maxPoolSize" value="${jdbc.maxconn}"/> <property name="idleConnectionTestPeriod" value="150"/> <property name="acquireIncrement" value="1"/> <property name="maxStatements" value="0"/> <property name="numHelperThreads" value="5"/> </bean> </beans> and this is the stack trace: 2010-06-13 12:16:33,526 INFO [org.springframework.web.context.ContextLoader] - < Root WebApplicationContext: initialization started> 2010-06-13 12:16:33,707 INFO [org.springframework.web.context.support.XmlWebAppl icationContext] - <Refreshing Root WebApplicationContext: startup date [Sun Jun 13 12:16:33 GMT-05:00 2010]; root of context hierarchy> 2010-06-13 12:16:34,086 INFO [org.springframework.beans.factory.xml.XmlBeanDefin itionReader] - <Loading XML bean definitions from ServletContext resource [/WEB- INF/yummy-servlet.xml]> 2010-06-13 12:16:34,378 INFO [org.springframework.beans.factory.xml.XmlBeanDefin itionReader] - <Loading XML bean definitions from URL [jndi:/localhost/protoweb/ WEB-INF/spring/applicationContext-hibernate.xml]> 2010-06-13 12:16:34,473 INFO [org.springframework.beans.factory.xml.XmlBeanDefin itionReader] - <Loading XML bean definitions from URL [jndi:/localhost/protoweb/ WEB-INF/spring/applicationContext-dataSource.xml]> 2010-06-13 12:16:35,098 ERROR [org.springframework.web.context.ContextLoader] - <Context initialization failed> org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [spring/applicationContext-hibernate.xml] Offending resource: ServletContext resource [/WEB-INF/yummy-servlet.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Un expected exception parsing XML document from URL [jndi:/localhost/protoweb/WEB-INF/spring/applicationContext-hibernate.xml]; nested exception is java.lang.NoSuchMethodError: org.springframework.beans.MutablePropertyValues.add(Ljava/lang/Str ing;Ljava/lang/Object;)Lorg/springframework/beans/MutablePropertyValues; at org.springframework.beans.factory.parsing.FailFastProblemReporter.err or(FailFastProblemReporter.java:68) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderC ontext.java:85) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderC ontext.java:76) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe ader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:197) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe ader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:146) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe ader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:131) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe ader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:91) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registe rBeanDefinitions(XmlBeanDefinitionReader.java:475) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadB eanDefinitions(XmlBeanDefinitionReader.java:372) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBea nDefinitions(XmlBeanDefinitionReader.java:316) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBea nDefinitions(XmlBeanDefinitionReader.java:284) at org.springframework.beans.factory.support.AbstractBeanDefinitionReade r.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReade r.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) at org.springframework.beans.factory.support.AbstractBeanDefinitionReade r.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) at org.springframework.web.context.support.XmlWebApplicationContext.load BeanDefinitions(XmlWebApplicationContext.java:125) at org.springframework.web.context.support.XmlWebApplicationContext.load BeanDefinitions(XmlWebApplicationContext.java:93) at org.springframework.context.support.AbstractRefreshableApplicationCon text.refreshBeanFactory(AbstractRefreshableApplicationContext.java:127) at org.springframework.context.support.AbstractApplicationContext.obtain FreshBeanFactory(AbstractApplicationContext.java:429) at org.springframework.context.support.AbstractApplicationContext.refres h(AbstractApplicationContext.java:356) at org.springframework.web.context.ContextLoader.createWebApplicationCon text(ContextLoader.java:270) at org.springframework.web.context.ContextLoader.initWebApplicationConte xt(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitiali zed(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContex t.java:3972) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4 467) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase .java:791) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:77 1) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:546) at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:905) at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:740 ) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:500 ) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1277) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java :321) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(Lifecycl eSupport.java:119) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053) at org.apache.catalina.core.StandardHost.start(StandardHost.java:785) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443 ) at org.apache.catalina.core.StandardService.start(StandardService.java:5 19) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710 ) at org.apache.catalina.startup.Catalina.start(Catalina.java:581) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces sorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Unexp ected exception parsing XML document from URL [jndi:/localhost/protoweb/WEB-INF/ spring/applicationContext-hibernate.xml]; nested exception is java.lang.NoSuchMe thodError: org.springframework.beans.MutablePropertyValues.add(Ljava/lang/String ;Ljava/lang/Object;)Lorg/springframework/beans/MutablePropertyValues; at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadB eanDefinitions(XmlBeanDefinitionReader.java:394) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBea nDefinitions(XmlBeanDefinitionReader.java:316) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBea nDefinitions(XmlBeanDefinitionReader.java:284) at org.springframework.beans.factory.support.AbstractBeanDefinitionReade r.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReade r.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe ader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:187) ... 42 more Caused by: java.lang.NoSuchMethodError: org.springframework.beans.MutablePropert yValues.add(Ljava/lang/String;Ljava/lang/Object;)Lorg/springframework/beans/Muta blePropertyValues; at org.springframework.transaction.config.AnnotationDrivenBeanDefinition Parser.registerTransactionManager(AnnotationDrivenBeanDefinitionParser.java:95) at org.springframework.transaction.config.AnnotationDrivenBeanDefinition Parser.access$0(AnnotationDrivenBeanDefinitionParser.java:94) at org.springframework.transaction.config.AnnotationDrivenBeanDefinition Parser$AopAutoProxyConfigurer.configureAutoProxyCreator(AnnotationDrivenBeanDefi nitionParser.java:121) at org.springframework.transaction.config.AnnotationDrivenBeanDefinition Parser.parse(AnnotationDrivenBeanDefinitionParser.java:79) at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(N amespaceHandlerSupport.java:72) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.pa rseCustomElement(BeanDefinitionParserDelegate.java:1327) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.pa rseCustomElement(BeanDefinitionParserDelegate.java:1317) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe ader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:134) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentRe ader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:91) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registe rBeanDefinitions(XmlBeanDefinitionReader.java:475) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadB eanDefinitions(XmlBeanDefinitionReader.java:372) ... 47 more 06/13/2010 12:16:35 PM org.apache.catalina.core.StandardContext start SEVERE: Error listenerStart

    Read the article

  • How do you test an ICF based connector using Connector Facade Standalone?

    - by Shashidhar Malyala
    Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} The following code helps in writing a standalone java program to test an ICF based connector. The sample code in this example takes into account an ICF based flatfile connector. It is possible to test various operations like create, update, delete, search etc... It is also possible to set values to the connector configuration parameters, add/remove attributes and their values. public class FlatFile { private static final java.lang.String BUNDLE_NAME = "<PACKAGE_NAME>"; //Ex: org.info.icf.flatfile private static final java.lang.String BUNDLE_VERSION = "1.0.0"; private static final java.lang.String CONNECTOR_NAME = "org.info.icf.flatfile.FlatFileConnector"; // Name of connector class i.e. the class implemting the connector SPI operations public ConnectorFacade getFacade() throws IOException { ConnectorInfoManagerFactory fact = ConnectorInfoManagerFactory .getInstance(); File bundleDirectory = new File("<BUNDLE_LOCATION>"); //Ex: /usr/oracle/connector_bundles/ URL url = IOUtil.makeURL(bundleDirectory, "org.info.icf.flatfile-1.0.0.jar"); ConnectorInfoManager manager = fact.getLocalManager(url); ConnectorKey key = new ConnectorKey(BUNDLE_NAME, BUNDLE_VERSION, CONNECTOR_NAME); ConnectorInfo info = manager.findConnectorInfo(key); // From the ConnectorInfo object, create the default APIConfiguration. APIConfiguration apiConfig = info.createDefaultAPIConfiguration(); // From the default APIConfiguration, retrieve the // ConfigurationProperties. ConfigurationProperties properties = apiConfig .getConfigurationProperties(); // Print out what the properties are (not necessary) List propertyNames = properties.getPropertyNames(); for (String propName : propertyNames) { ConfigurationProperty prop = properties.getProperty(propName); System.out.println("Property Name: " + prop.getName() + "\tProperty Type: " + prop.getType()); } properties .setPropertyValue("fileLocation", "/usr/oracle/accounts.csv"); // Set all of the ConfigurationProperties needed by the connector. // properties.setPropertyValue("host", FOOBAR_HOST); // properties.setPropertyValue("adminName", FOOBAR_ADMIN); // properties.setPropertyValue("adminPassword", FOOBAR_PASSWORD); // properties.setPropertyValue("useSSL", false); // Use the ConnectorFacadeFactory's newInstance() method to get a new // connector. ConnectorFacade connFacade = ConnectorFacadeFactory.getInstance() .newInstance(apiConfig); // Make sure we have set up the Configuration properly connFacade.validate(); return connFacade; } public static void main(String[] args) throws IOException { FlatFile file = new FlatFile(); ConnectorFacade cfac = file.getFacade(); Set attrSet = new HashSet(); attrSet.add(AttributeBuilder.build(Name.NAME, "Test01")); attrSet.add(AttributeBuilder.build("FIRST_NAME", "Test_First")); attrSet.add(AttributeBuilder.build("LAST_NAME", "Test_Last")); //Create Uid uid = cfac.create(ObjectClass.ACCOUNT, attrSet, null); //Delete Uid uidP = new Uid("Test01"); cfac.delete(ObjectClass.ACCOUNT, uidP, null); } }

    Read the article

  • How to list all (groovy) classes in JVM in groovy

    - by Dan
    I am writing a DelegatingMetaClass that I would like to apply to all groovy classes in my project, but I do not how to get hold of all classes in the project? Here is the code: /* This will work ok, since I know Foo beforehand, but what about classes that do not exist yet? */ def myMetaClass = new DelegatingMetaClass(Foo.class) InvokerHelper.metaRegistry.setMetaClass(Foo.class, myMetaClass) /* how to do this? allGroovyClasses.each{ def myMetaClass = new DelegatingMetaClass(it) InvokerHelper.metaRegistry.setMetaClass(it, myMetaClass) } */ class SimpleInterceptor extends DelegatingMetaClass{ public SimpleInterceptor(final Class aclass) { super(aclass); initialize(); } public Object getProperty(Object object, String prop) { println ("I am in a property interceptor!!!") return super.getProperty(object, prop) } public Object invokeMethod(Object a_object, String a_methodName, Object[] a_arguments) { println ("I am in a method interceptor!!!") return super.invokeMethod(a_object, a_methodName, a_arguments) }

    Read the article

  • How can I disable multiple links with jQuery?

    - by Samantha J
    I have the following HTML: <a title="Login" data-href="/MyAccount/Access/Login" data-title="Admin" data-entity="n/a" id="loginLink" class="nav-button dialogLink"><b>Login</b></a> <a title="Register" data-href="/MyAccount/Access/Register" data-title="Admin" data-entity="n/a" id="registerLink" class="nav-button dialogLink"><b>Register</b></a> When a user clicks on the #loginLink or #registerLink I would like to disable the link and call a dialog script. I created the following function: $("#loginLink, #registerLink") .click(function () { $('#loginLink').prop('disabled', true); $('#registerLink').prop('disabled', true); dialog(this); }); It calls the dialog correctly but doesn't disable the links and if I click the buttons more than once it calls up more than one dialog box. Is there something I am doing wrong? I can't see why it would not work.

    Read the article

  • Approaches for generic, compile-time safe lazy-load methods

    - by Aaronaught
    Suppose I have created a wrapper class like the following: public class Foo : IFoo { private readonly IFoo innerFoo; public Foo(IFoo innerFoo) { this.innerFoo = innerFoo; } public int? Bar { get; set; } public int? Baz { get; set; } } The idea here is that the innerFoo might wrap data-access methods or something similarly expensive, and I only want its GetBar and GetBaz methods to be invoked once. So I want to create another wrapper around it, which will save the values obtained on the first run. It's simple enough to do this, of course: int IFoo.GetBar() { if ((Bar == null) && (innerFoo != null)) Bar = innerFoo.GetBar(); return Bar ?? 0; } int IFoo.GetBaz() { if ((Baz == null) && (innerFoo != null)) Baz = innerFoo.GetBaz(); return Baz ?? 0; } But it gets pretty repetitive if I'm doing this with 10 different properties and 30 different wrappers. So I figured, hey, let's make this generic: T LazyLoad<T>(ref T prop, Func<IFoo, T> loader) { if ((prop == null) && (innerFoo != null)) prop = loader(innerFoo); return prop; } Which almost gets me where I want, but not quite, because you can't ref an auto-property (or any property at all). In other words, I can't write this: int IFoo.GetBar() { return LazyLoad(ref Bar, f => f.GetBar()); // <--- Won't compile } Instead, I'd have to change Bar to have an explicit backing field and write explicit getters and setters. Which is fine, except for the fact that I end up writing even more redundant code than I was writing in the first place. Then I considered the possibility of using expression trees: T LazyLoad<T>(Expression<Func<T>> propExpr, Func<IFoo, T> loader) { var memberExpression = propExpr.Body as MemberExpression; if (memberExpression != null) { // Use Reflection to inspect/set the property } } This plays nice with refactoring - it'll work great if I do this: return LazyLoad(f => f.Bar, f => f.GetBar()); But it's not actually safe, because someone less clever (i.e. myself in 3 days from now when I inevitably forget how this is implemented internally) could decide to write this instead: return LazyLoad(f => 3, f => f.GetBar()); Which is either going to crash or result in unexpected/undefined behaviour, depending on how defensively I write the LazyLoad method. So I don't really like this approach either, because it leads to the possibility of runtime errors which would have been prevented in the first attempt. It also relies on Reflection, which feels a little dirty here, even though this code is admittedly not performance-sensitive. Now I could also decide to go all-out and use DynamicProxy to do method interception and not have to write any code, and in fact I already do this in some applications. But this code is residing in a core library which many other assemblies depend on, and it seems horribly wrong to be introducing this kind of complexity at such a low level. Separating the interceptor-based implementation from the IFoo interface by putting it into its own assembly doesn't really help; the fact is that this very class is still going to be used all over the place, must be used, so this isn't one of those problems that could be trivially solved with a little DI magic. The last option I've already thought of would be to have a method like: T LazyLoad<T>(Func<T> getter, Action<T> setter, Func<IFoo, T> loader) { ... } This option is very "meh" as well - it avoids Reflection but is still error-prone, and it doesn't really reduce the repetition that much. It's almost as bad as having to write explicit getters and setters for each property. Maybe I'm just being incredibly nit-picky, but this application is still in its early stages, and it's going to grow substantially over time, and I really want to keep the code squeaky-clean. Bottom line: I'm at an impasse, looking for other ideas. Question: Is there any way to clean up the lazy-loading code at the top, such that the implementation will: Guarantee compile-time safety, like the ref version; Actually reduce the amount of code repetition, like the Expression version; and Not take on any significant additional dependencies? In other words, is there a way to do this just using regular C# language features and possibly a few small helper classes? Or am I just going to have to accept that there's a trade-off here and strike one of the above requirements from the list?

    Read the article

  • How to get object properties of specific class in SPARQL

    - by udayalkonline
    hi, I have some ontology(campus.owl).There are tree classes(Student,Sport,Lecturer).Student class is joined with Lecturer class using "has" object property and Student class joined with Sport class with "isPlay" object property. problem I want to get the object property between Student and Lecturer using some SPARQL query. PREFIX rdfs: http://www.w3.org/2000/01/rdf-schema# PREFIX rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns# PREFIX my: http://www.semanticweb.org/ontologies/2010/5/Ontology1275975684120.owl# SELECT ?prop WHERE { ?prop ..........??? } Any Idea..?? Thank in advance!

    Read the article

  • DataAnnotation attributes buddy class strangeness - ASP.NET MVC

    - by JK
    Given this POCO class that was automatically generated by an EntityFramework T4 template (has not and can not be manually edited in any way): public partial class Customer { [Required] [StringLength(20, ErrorMessage = "Customer Number - Please enter no more than 20 characters.")] [DisplayName("Customer Number")] public virtual string CustomerNumber { get;set; } [Required] [StringLength(10, ErrorMessage = "ACNumber - Please enter no more than 10 characters.")] [DisplayName("ACNumber")] public virtual string ACNumber{ get;set; } } Note that "ACNumber" is a badly named database field, so the autogenerator is unable to generate the correct display name and error message which should be "Account Number". So we manually create this buddy class to add custom attributes that could not be automatically generated: [MetadataType(typeof(CustomerAnnotations))] public partial class Customer { } public class CustomerAnnotations { [NumberCode] // This line does not work public virtual string CustomerNumber { get;set; } [StringLength(10, ErrorMessage = "Account Number - Please enter no more than 10 characters.")] [DisplayName("Account Number")] public virtual string ACNumber { get;set; } } Where [NumberCode] is a simple regex based attribute that allows only digits and hyphens: [AttributeUsage(AttributeTargets.Property)] public class NumberCodeAttribute: RegularExpressionAttribute { private const string REGX = @"^[0-9-]+$"; public NumberCodeAttribute() : base(REGX) { } } NOW, when I load the page, the DisplayName attribute works correctly - it shows the display name from the buddy class not the generated class. The StringLength attribute does not work correctly - it shows the error message from the generated class ("ACNumber" instead of "Account Number"). BUT the [NumberCode] attribute in the buddy class does not even get applied to the AccountNumber property: foreach (ValidationAttribute attrib in prop.Attributes.OfType<ValidationAttribute>()) { // This collection correctly contains all the [Required], [StringLength] attributes // BUT does not contain the [NumberCode] attribute ApplyValidation(generator, attrib); } Why does the prop.Attributes.OfType<ValidationAttribute>() collection not contain the [NumberCode] attribute? NumberCode inherits RegularExpressionAttribute which inherits ValidationAttribute so it should be there. If I manually move the [NumberCode] attribute to the autogenerated class, then it is included in the prop.Attributes.OfType<ValidationAttribute>() collection. So what I don't understand is why this particular attribute does not work in when in the buddy class, when other attributes in the buddy class do work. And why this attribute works in the autogenerated class, but not in the buddy. Any ideas? Also why does DisplayName get overriden by the buddy, when StringLength does not?

    Read the article

  • How to specify character encoding for Ant Task parameters in Java

    - by räph
    I'm writing an ANT task in Java. In my build.xml I specify parameters, which should be read from my java class. Problems occur, when I use special characters, like german umlauts (Ö,Ä,Ü) in these parameters. In my java task they appear as ?-characters (using System.out.print). All my files are encoded as UTF-8. and my build.xml has the corresponding declaration: <?xml version="1.0" encoding="UTF-8" ?> For the details of writing the task: I do it according to http://ant.apache.org/manual/develop.html (especially Point 5 nested elements). I have nested elements in my task like: <parameter name="test" value="ÖÄÜtest"/> and a java method: public void addConfiguredParameter(Parameter prop) { System.out.println(prop.getValue()); //prints ???test } to read the parameter values.

    Read the article

  • Using image resource in XAML markup?

    - by Jeff Dahmer
    I'm trying to add little icons to my tabs in WPF but having trouble with how to set up the binding. <TabItem.Header> <StackPanel Orientation="Horizontal"> <Image Source="{Binding Source=prop:Resources.eye}" /> <Label VerticalAlignment="Center">Header</Label> </StackPanel> </TabItem.Header> The xmlns:prop is set up for the local project's Properties, I am pulling other values from it elsewhere so I know that the namespace works. The markup above compiles fine BUT I don't see the eye image in the tab. Also, is there any way to set this up into a template? I'm fairly new to XAML/WPF and each tab will have its own image...

    Read the article

  • How to modify PropertyGrid at runtime (add/remove property and dynamic types/enums)

    - by salle55
    How do you modify a propertygrid at runtime in every way? I want to be able to add and remove properties and add "dynamic types", what I mean with that is a type that result in a runtime generated dropdown in the propertygrid using a TypeConverter. I have actually been able to do both those things (add/remove properties and add dynamic type) but only separately not at the same time. To implement the support to add and remove properties at runtime I used this codeproject article and modified the code a bit to support different types (not just strings). private System.Windows.Forms.PropertyGrid propertyGrid1; private CustomClass myProperties = new CustomClass(); public Form1() { InitializeComponent(); myProperties.Add(new CustomProperty("Name", "Sven", typeof(string), false, true)); myProperties.Add(new CustomProperty("MyBool", "True", typeof(bool), false, true)); myProperties.Add(new CustomProperty("CaptionPosition", "Top", typeof(CaptionPosition), false, true)); myProperties.Add(new CustomProperty("Custom", "", typeof(StatesList), false, true)); //<-- doesn't work } /// <summary> /// CustomClass (Which is binding to property grid) /// </summary> public class CustomClass: CollectionBase,ICustomTypeDescriptor { /// <summary> /// Add CustomProperty to Collectionbase List /// </summary> /// <param name="Value"></param> public void Add(CustomProperty Value) { base.List.Add(Value); } /// <summary> /// Remove item from List /// </summary> /// <param name="Name"></param> public void Remove(string Name) { foreach(CustomProperty prop in base.List) { if(prop.Name == Name) { base.List.Remove(prop); return; } } } etc... public enum CaptionPosition { Top, Left } My complete solution can be downloaded here. It works fine when I add strings, bools or enums, but when I try to add a "dynamic type" like StatesList it doesn't work. Does anyone know why and can help me to solve it? public class StatesList : System.ComponentModel.StringConverter { private string[] _States = { "Alabama", "Alaska", "Arizona", "Arkansas" }; public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(_States); } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } } The method of using a TypeConverter works fine when you don't try to add the property at runtime, for example this code works without any problem, but I want to be able to do both. Please take a look at my project. Thanks!

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >