Zend: Accessing model from Bootstrap raises an exception - exception

This is the code I have in Bootstrap:
public function _initRegistry()
{
$systemConfigModel = new Application_Model_DbTable_SystemConfig();
Zend_Registry::set('config', $systemConfigModel->getSystemConfig());
}
And this an exception I am getting:
( ! ) Fatal error: Uncaught exception 'Zend_Db_Table_Exception' with message 'No adapter found for Application_Model_DbTable_SystemConfig' in /usr/share/php5/Zend/Db/Table/Abstract.php on line 755
( ! ) Zend_Db_Table_Exception: No adapter found for Application_Model_DbTable_SystemConfig in /usr/share/php5/Zend/Db/Table/Abstract.php on line 755
It works just fine if I call it within my BaseController. It just looks like the PDO adapter that I specify in application.ini has not been initialized at the time Bootstrap is executed (strange?). What should I do to make the code work in Bootstrap? Is it necessary to create and set an adapter with Zend_Db_Table::setDefaultAdapter();?
I am asking because if the code is not in Bootstrap, it needs to be duplicated in two different places and it also kind of looks like it belongs to Bootstrap.

You are correct, during bootstrap, the Zend Application resource for your database has not yet been initialized.
Try changing your bootstrap method as follows so you explicitly bootstrap the db resource.
public function _initRegistry()
{
$this->bootstrap('db'); // Bootstrap the db resource from configuration
$db = $this->getResource('db'); // get the db object here, if necessary
// now that you have initialized the db resource, you can use your dbtable object
$systemConfigModel = new Application_Model_DbTable_SystemConfig();
Zend_Registry::set('config', $systemConfigModel->getSystemConfig());
}

Related

How to fix Glass Mapper error - failed to find configuration for parent item type?

I have a Sitecore 8.1 CD instance. I also have some code that needs to create a content item in the Master database. (I am aware that is a no-no but I just need to figure this out at the moment) When my code attempts to use Glass Mapper to create a content item I get an error. Here is the code snippet and the error message. I am just trying to understand what the error means. I have a sense that this is simply a configuration problem. This code works fine on our Sitecore CM server. So I am hoping that by simply adjusting the config on our CD server I can get this to work. So far I have re-enabled the Master entry in ConnectionStrings.config and in Sitecore.config. But that hasn't fixed this.
SitecoreService service = new SitecoreService("master");
SimpleAes aes = new SimpleAes();
using (new SecurityDisabler())
{
Item parentItem = Factory.GetDatabase("master").GetItem("/sitecore/content/Non Page Content/Account Information/Shipping Addresses");
newAddress = service.Create(parentItem, newAddress); //THIS IS WHERE THE CODE FAILS
user.Addresses.Add(newAddress);
Utility.PublishItem(service.ResolveItem(newAddress));
id = aes.EncryptToString(newAddress.Id.ToString());
user.Addresses = user.Addresses;
user.Save();
}
Error Message:
Glass.Mapper.MapperException: Failed to find configuration for parent
item type Sitecore.Data.Items.Item ---> System.NullReferenceException:
Object reference not set to an instance of an object. at
System.Object.GetType() at
Glass.Mapper.Context.GetTypeConfiguration[T](Object obj, Boolean
doNotLoad, Boolean checkBase) at
Glass.Mapper.Sc.SitecoreService.Create[T,TK](TK parent, T newItem,
Boolean updateStatistics, Boolean silent) --- End of inner exception
stack trace --- at Glass.Mapper.Sc.SitecoreService.Create[T,TK](TK
parent, T newItem, Boolean updateStatistics, Boolean silent)
It is failing on this line
Item parentItem = Factory.GetDatabase("master").GetItem("/sitecore/content/Non Page Content/Account Information/Shipping Addresses");
if you put a check around it saying
if (parentItem != null) { // your code }
Then the code will work through and you will not get exception, but nothing will happen as well if parentItem is null.
Quick fix solution will be to give a 'master' DB connection string on your CD server (which is a no-no as you said). Better solution will be to expose master database through Sitecore Item API or your custom API, securing it through authentication and then calling this code from CD server via API.
I am not sure if you still are looking how to solve this issue, but when I faced today with it I found your question.
Problem is that your parentItem has type Item. It causes issue inside in Glass.
You can use any type as parent, but limitation is that it should not be inherited from Sitecore Item class.
Try this:
var parentItem = Factory.GetDatabase("master").GetItem("/sitecore/content/Non Page Content/Account Information/Shipping Addresses").GlassCast<BaseSitecoreItem>();
newAddress = service.Create(parentItem, newAddress);
where BaseSitecoreItem is some your Glass Model.
It helped me and hope will help you.

How to access to a function of a controller from inside another controller in Symfony2?

I would like to know how to access to a function of a controller from inside another controller in Symfony2. In fact I have two controllers: "EventgroupeController" and "GroupeController". In the code of the controller "EventgroupeController" I put the instruction below:
return GroupeController::AfficheGroupeAction();
But when I run the code (or let's say the project I am developing), it displays this error message in Symfony2:
ContextErrorException: Runtime Notice: Non-static method Ikproj\GroupeBundle\Controller\GroupeController::AfficheGroupeAction() should not be called statically, assuming $this from incompatible context in C:\wamp\www\Wkayet_project\PFESymfony2\src\Ikproj\GroupeBundle\Controller\EventgroupeController.php line 104
After having a look at this link: How to access a different controller from inside a controller Symfony2 in order to know how to access a different controller from inside a controller in Symfony2, I modified the content of the file services.yml as below:
parameters:
# ikproj_groupe.example.class: Ikproj\GroupeBundle\Example
services:
# ikproj_groupe.example:
# class: %ikproj_groupe.example.class%
# arguments: [#service_id, "plain_value", %parameter%]
controllerservice:
class: Ikproj\GroupeBundle\Controller\GroupeController
Then, I replaced the instruction: return GroupeController::AfficheGroupeAction(); by the lines below:
$yourController = $this->get('controllerservice');
$yourController1 = $yourController::AfficheGroupeAction();
return $yourController1;
But I still see this error message:
ContextErrorException: Runtime Notice: Non-static method Ikproj\GroupeBundle\Controller\GroupeController::AfficheGroupeAction() should not be called statically, assuming $this from incompatible context in C:\wamp\www\Wkayet_project\PFESymfony2\src\Ikproj\GroupeBundle\Controller\EventgroupeController.php line 106
So, my question is: how can I resolve this problem and how can I access to the function AfficheGroupeAction() of the controller "GroupeController" from inside the controller "EventgroupeController"?
An action method must not be static.
$this->get('controllerservice')->youMethod();
Should work !
But with a good "application design", you should not have this need except if you want to forward a request from a controller to another ( example : backward compatibility ). In this case you can use the forward method provided by symfony2 base controller. ( http://symfony.com/doc/current/book/controller.html )

how to get getPooledConnection() on MysqlConnectionPoolDataSource

I have a class where i want the pool connection . I created MysqlConnectionPoolDataSource object and on that i'm calling the getPooledConnection() method like this
MysqlConnectionPoolDataSource datasource;
PooledConnection pconn=null;
pconn = dataSource.getPooledConnection();
when i am run the test class i am unable to get ant thing in
pconn = dataSource.getPooledConnection(); That is dataSource.getPooledConnection() returning nothing. How to fix this issue.
Thanks
Since you are using MysqlConnectionPoolDataSource in a test and not a Java EE container, you need to configure the object. At the very least I appears you will need to call setUrl(), setUser() and setPassword()

NUnit / Moq throwing a NullReferenceException error on the constructor of a variable

I am using Moq, NUnit, WPF, MVVM, Ninject.
I am writing a test for my LoginViewModel, and in the test when I use the constructor of the LoginViewModel to create a new instance, I am getting a NullReferenceException error. The code compiles and runs, (i.e. when I run the program the LoginView shows, and works with the LoginViewModel to create the correct behaviour etc) but for some reason the UnitTest is crashing.
this is the constructor:
public LoginViewModel(ILoginServices loginServices,IDialogService dialogServices)
{
InitializeFields();
_loginServices = loginServices;
_dialogService = dialogServices;
DomainList = _loginServices.GetDomainListing();
}
I have mocked the dependencies as follows:
Mock<ILoginServices> moq = new Mock<ILoginServices>();
moq.Setup(log =>
log.LoginUser(It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>()))
.Callback<string, string, string>((i, j, k) => CheckArgs(i, j, k));
moq.Setup(log2 =>
log2.GetDomainListing()).Returns(new List<string> { "Domain" });
Mock<IDialogService> moq2 = new Mock<IDialogService>();
I have also tried inserting real services as the parameters.
I have verified that the mocks do work, and the objects these mocks
return are not null.
I have commented out all the code in the constructor.
I have tried inserting the line
LoginViewModel test = new LoginViewModel(_fakeLoginService,_fakeDialogService);
in front of the call to the constructor (to see if it had to do with the original local variable being disposed or something before) and this line crashed instead.
From all I can see this must be the constructor,(but not the code I have written inside it) and that this is solely related to NUnit / Moq as my code still compiles and runs fine.
I have no idea on this one guys, can anyone point me in the right direction?
[Edit]
Ok so I have run through the code and the error comes from this line of code:
ImageSource = (ImageSource)Application.Current.FindResource(_imageName);
This code is going to a ImageDictionary and getting a reference to the image for an undo button in the WindowViewModel (which my LoginViewModel inherits).
My hypotheses as to why its working in the normal running of the application, but not in the testing are:
1) Because I am running the program code through NUnit, the Application.Current object isnt getting property assigned/there is no Application.Current object to get.
**or**
2) Something to do with the fact that because the program code is being run in NUnit, the code doesn't have access to/can't resolve the ImageDictionary to find the image.
I'm leaning more strongly to the first hypothesis, but I'm as of yet not 100% sure, and I am having trouble finding the values of the Application.Current at runtime, cause when I move my cursor over the code the tooltip that normally appears showing the detail of the object that is not appearing.
My new question is: Does any of this make sense? Do you guys know if the Application.Current object exists / can be accessed when running the testing project through NUnit?
Any help will be appreciated.
You are correct. Application.Current is null for Unit tests. You can work around this by injecting the Application object as referencing singletons in code can make life tricky.

How do you bind elements to SwiXML in JRuby?

I am trying to recreate SwiXML examples in JRuby. But the objects
created in JRuby never seem to be visible to SwiXML. Here is an example.
<frame size="200,200" title="Action Test">
<menubar>
<menu text="File">
<menuitem action="quit" accelerator="meta X" />
</menu>
</menubar>
<button action="quit" text="A Quit Button"
ToolTipText="This is a quit button." />
</frame>
The Java code from the SwiXML example is as follows:
public class ActionTest {
// Create an Action as a member variable
public Action quit = new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
};
public ActionTest() throws Exception {
// set the Action's name
quit.putValue(Action.NAME, "Quit");
// build the GUI
new SwingEngine(this).render("ActionTest.xml")
.setVisible(true);
}
public static void main(String[] args) throws Exception {
new ActionTest();
}
}
I have created some JRuby code to correspond to this, but it seems as if
the #quit member is never seen. Also tried referencing other named
elements (not in this example):
require 'java'
require 'java/swixml.jar'
require 'java/jdom.jar'
include_class 'javax.swing.AbstractAction'
include_class 'javax.swing.Action'
include_class 'javax.swing.JButton'
class MyAction < AbstractAction
def actionPerformed(ae)
exit # puts "Clicked"
end
end
class Main < Object # Java::JavaLang::Object
def initialize
#quit = MyAction.new
#quit.putValue(Action.NAME, "Quit")
#f = java.io.File.new("sample.xml")
#se = org.swixml.SwingEngine.new(self).render(#f).setVisible(true)
end
end
Main.new
I've been struggling with integrating JRuby and SwiXml this week. I've come to the conclusion that you can't have SwiXml automatically bind your variables/actions from the XML. (I think this is because in Java the variables already exist, whereas in JRuby they are created 'on-the-fly', so SwiXml isn't sure what to do. That's my conclusion, anyway, after hours of digging through source code. JRuby is fairly new to me, so someone more advanced might be able to tell me why this won't work.)
The solution is to simply bind them manually in the JRuby code. It's actually fairly easy, since this is Ruby.
include Java
java_import 'org.swixml.SwingEngine'
class HelloWorld
def initialize
#swix = SwingEngine.new(self)
#swix.render("xml/helloworld.xml")
btn = #swix.find("submit")
btn.add_action_listener { |event| btn.text = 'Hi' }
end
def run
#swix.getRootComponent.setVisible(true)
end
end
See? Not too bad. In my case, "submit" is defined as the <button>'s ID attribute. So in my XML file I have <button text="Click Here" id="submit" /> Think of the find() method like a findById() method (if you're familiar with DOM manipulation through JavaScript...).
Note that since the add_action_listener takes a block, instance variables (ivars) can be included in the block (in other words, it acts like you would expect a Java anonymous class/block to work). There's other ways to implement/add an action listener. See this page: https://github.com/jruby/jruby/wiki/FAQs and scroll down to the section with a heading that says How can I implement a Java Interface using a Ruby Class?
Any element (as far as I know), can be retrieved by the SwingEngine class's find() method, as long as it's id is defined in the XML file.
A few minor things: include_class is now deprecated. You should use java_import instead. Also, your class that you're passing to SwingEngine does not need to inherit from Object or anything like that. JRuby is getting much better about making things more 'ruby-like' when integrating with Java.
Hope this helps. There's not much info out there about this stuff.
P.S. I found the info about 'manually binding' from this link: http://www.mail-archive.com/forum#carlsbadcubes.com/msg00062.html
I don't have your answer here (My Ruby isn't good enough) - but I having a similar issue trying to use Jython here; this example partially works (it picks up the 'quit' action).
from org.swixml.jsr296 import SwingApplication
from org.jdesktop.application import Application
from javax.swing import JButton, JFrame
class MyFrame(JFrame):
def __init__(self):
pass
class Tester(SwingApplication):
def __init__(self):
self.frame=MyFrame()
#self.frame=JFrame()
def startup(self):
print "Application Started"
self.render(self.frame,"frame.xml").show()
def shutdown(self):
print "Application Shutdown"
#def quit(self,evt):
# print "Over-ridden quit"
def action1(self,evt):
print "action1"
if __name__=='__main__':
Application.launch(Tester,None)
I added in a second button in the XML like this:
<button action="action1" text="action1" ToolTipText="action1" />
But the additional 'action1' method is never seen by swixml it seems, I get the following output when I start (and then quit) the application:
Application Started
SwixML 2.5
11-Nov-2011 12:10:38 org.swixml.XAction <init>
WARNING: error on Action initialization [org.python.proxies.__main__$MyFrame$1.action1()]
Application Shutdown
The interesting thing is, if you uncomment the 'def quit(self,evt)' method ; this method IS seen by SXIWML; and the behaviour of the 'quit' button changes from shutting down the Application to printing out a message.
So it seems that something about the way SWIXML reflects to look for actions fails when the action is purely defined in Jython (Method signatures?): but over-riding an existing action method does work.
It would be really nice to see what is going on here - I might log a new StackOverFlow question on this example and reference this one.
It would be great to be able to quickly throw together simple SWING apps using JRuby / Jython (etc) using SWIXMl; but a working template of how to do this is needed I think.
The other strange thing that I cannot explain ; if the line 'self.frame=MyFrame()' is changed to instantiate a standard JFrame: 'self.frame.JFrame()' - this results in classloader errors:
SwixML 2.5
11-Nov-2011 12:19:14 org.swixml.XAction <init>
WARNING: error on Action initialization [null ClassLoader]
11-Nov-2011 12:19:14 org.swixml.XAction <init>
WARNING: error on Action initialization [null ClassLoader]
11-Nov-2011 12:19:14 org.swixml.XAction <init>
WARNING: error on Action initialization [null ClassLoader]