Is there a way to gracefully check whether a page exists in EpiServer CMS 5 (given a pageId integer) without having to catch the PageNotFoundException thrown by
DataFactory.Instance.GetPage(pageReference)
(EpiServer will happily create a PageReference using a non existing pageId).
Surely I can check whether a page exists without throwing an exception or doing a massive loop?
[EPiServer CMS 5 R2 SP2]
No, not without bypassing the page cache and that is more expensive than catching the exception.
I find it nice to do the catching in an extension method:
public static bool TryGetPage(this PageReference pageReference, out PageData pd)
{
try
{
pd = DataFactory.Instance.GetPage(pageReference);
return true;
}
catch (Exception)
{
pd = null;
return false;
}
}
There is a static method of PageReference which should help:
PageReference.IsNullOrEmpty(pageLink)
Related
I am trying to integrate Hystrix javanica into my existing java EJB web application and facing 2 issues with running it.
When I try to invoke following service it always returns response from fallback method and I see that the Throwable object in fallback method has "com.netflix.hystrix.exception.HystrixTimeoutException" exception.
Each time this service is triggered, HystrixCommad and fallback methods are called multiple times around 50 times.
Can anyone suggest me with any inputs? Am I missing any configuration?
I am including following libraries in my project.
project libraries
I have setup my aspect file as follows:
<aspectj>
<weaver options="-verbose -showWeaveInfo"></weaver>
<aspects>
<aspect name="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
</aspects>
</aspectj>
Here is my config.properties file in META-INF/config.properties
hystrix.command.default.execution.timeout.enabled=false
Here is my rest service file
#Path("/hystrix")
public class HystrixService {
#GET
#Path("clusterName")
#Produces({ MediaType.APPLICATION_JSON })
public Response getClusterName(#QueryParam("id") int id) {
ClusterCmdBean clusterCmdBean = new ClusterCmdBean();
String result = clusterCmdBean.getClusterNameForId(id);
return Response.ok(result).build();
}
}
Here is my bean class
public class ClusterCmdBean {
#HystrixCommand(groupKey = "ClusterCmdBeanGroup", commandKey = "getClusterNameForId", fallbackMethod = "defaultClusterName")
public String getClusterNameForId(int id) {
if (id > 0) {
return "cluster"+id;
} else {
throw new RuntimeException("command failed");
}
}
public String defaultClusterName(int id, Throwable e) {
return "No cluster - returned from fallback:" + e.getMessage();
}
}
Thanks for the help.
If you want to ensure you are setting the property, you can do that explicitly in the circuit annotation itself:
#HystrixCommand(commandProperties = {
#HystrixProperty(name = "execution.timeout.enabled", value = "false")
})
I would only recommend this for debugging purposes though.
Something that jumps out to me is that Javanica uses AspectJ AOP, which I have never seen work with new MyBean() before. I've always have to use #Autowired with Spring or similar to allow proxying. This could well just be something that is new to me though.
If you set a breakpoint inside the getClusterNameForId can you see in the stack trace that its being called via reflection (which it should be AFAIK)?
Note you can remove commandKey as this will default to the method name. Personally I would also remove groupKey and let it default to the class name.
Iam developing an Email application on Android and I got stuck at here. If I use Gmail server I can search Email by ID
SearchTerm term = new MessageIDTerm(ID);
message_s = folder.search(term);
But with this code, I can't search email with some Other server like yahoo,hotmail. And I try solve this bug by override this code
SearchTerm messageIDTerm= new SearchTerm() {
#Override
public boolean match(Message message) {
try {
String messageID="";
Enumeration headers = message.getAllHeaders();
while (headers.hasMoreElements()) {
eader h = (Header) headers.nextElement();
String mID = h.getName();
if(mID.contains("Message-ID") || mID.contains("Message-Id")){
messageID= h.getValue();
}
}
if (messageID.contains(ID)) {
return true;
}
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
};
message_s = folder.search(messageIDTerm);
It's success to search mail. But the problem is this code check every Message-ID by client search(download messeage-ID and compare) and it take a lot of time to find the result.
The first way, server make a seach for my request and its very fast.
So how do I make the search as fast as the first way if I use the second way?
Some servers are broken. You can't fix them.
If you have to do the search in the client, the best you can do is use the Folder.fetch method to prefetch the headers you're going to need to do the search. Then use the standard MessageIDTerm with the Message.match method as you iterate over all the messages you need to check.
I'm currently working with Integration Services (SSIS) to load a big amount of XML files into a SQL server database. Each XML file content needs to be dispatched in several tables. I have at least 10000 xml files to load using the process. Everything works fine till 6000 files are loaded. After 6000 treatment, I always got an OutOfMemoryException from my first dataflow task, the first in the process.
In this script component, I just check if a value from a XML file is already present in a specific database table. If it is present, I return the matched ID, otherwise, I add a new record. To achieve it, I use a Lookup component. I use it with No cache option, for memory matter. Then in case of matching, I process the return ID in a script component. Like I said, everything works fine until more or less 6000 files are processed. After I got :
Description : System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.HandleUserException(Exception e)
at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.PreExecute()
at Microsoft.SqlServer.Dts.Pipeline.ManagedComponentHost.HostPreExecute(IDTSManagedComponentWrapper100 wrapper)
Do you have some suggestions or some ressources which deal with performance and memory issue in SSIS ? Do you encountered similar problem ? DO you have an idea from where this memory problem could come from?
Thanks :)
EDIT:
Here is the code to check an XML against an XSD file. Can you see any memory leak?
public void Main()
{
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("", Dts.Variables["XSDFilePath"].Value.ToString());
settings.ValidationType = ValidationType.Schema;
using (XmlReader reader = XmlReader.Create(Dts.Variables["XMLFilePath"].Value.ToString(), settings))
{
XmlDocument document = new XmlDocument();
document.Load(reader);
ValidationEventHandler eventHandler = new ValidationEventHandler(XMLValidationHandler);
document.Validate(eventHandler);
}
if (ValidationResult)
{
Dts.TaskResult = (int)ScriptResults.Success;
}
else
{
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
catch (Exception ex)
{
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
private void XMLValidationHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
Console.WriteLine("Warning {0}", e.Message);
ValidationResult = false;
break;
case XmlSeverityType.Warning:
Console.WriteLine("Warning {0}", e.Message);
break;
}
}
Don't use the XMLDocument Object, It will load the entire document into memory and is likely the cause of your memory problem. Try instead to use the XmlValidatingReader
http://msdn.microsoft.com/en-us/library/system.xml.xmlvalidatingreader.aspx
It should provide a more efficient use of memory.
Refer to the 'answers' in this.,
http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/4d90afc8-0a1c-418f-9e3a-0b766f581b2c/
I have a Windows Phone 7 application built with silverlight. This application has been deployed. I've noticed in the log files that occasionally, my user's actions throw a "NotSupportedException". I have not been able to produce this. However, because of my logs, I know that it is happening in the Execute method shown here:
public void Execute()
{
try
{
// 1. Build the query
string serviceUrl = GetServiceUrl;
// 2. Asynchronously execute the query using HttpWebRequest
WebRequest request = HttpWebRequest.Create(serviceUrl);
request.BeginGetResponse(new AsyncCallback(ServiceRequest_Completed), request);
} catch (Exception ex)
{
LogException(ex, "1");
}
}
private void ServiceRequest_Completed(IAsyncResult result)
{
try
{
// 1. Get the response from the service call
WebRequest request = (WebRequest)(result.AsyncState);
WebResponse response = request.EndGetResponse(result);
// 2. Do stuff with response
}
catch (Exception ex)
{
LogException(ex, "2");
}
}
I know it is happening in the Execute method because the "1" is written in the log file instead of the "2" My question is, what would cause this? I looked at the MSDN documentation and it looks like I'm doing what I should be doing. Like I said, I can't reproduce it locally. But I do know that it is happening regularly by different users because of the log files.
There is a previous question with a very similar title - https://stackoverflow.com/questions/4053197/httpwebrequest-leads-me-to-system-notsupportedexception
The answer to that problem seems to have been using ServiceRequest_Completed instead of new AsyncCallback(ServiceRequest_Completed)
Given a pack:// URI, what's the best way to tell whether a compiled resource (e.g. a PNG image, compiled with a Build Action of "Resource") actually exists at that URI?
After some stumbling around, I came up with this code, which works but is clumsy:
private static bool CanLoadResource(Uri uri)
{
try
{
Application.GetResourceStream(uri);
return true;
}
catch (IOException)
{
return false;
}
}
(Note that the Application.GetResources documentation is wrong -- it throws an exception if the resource isn't found, rather than returning null like the docs incorrectly state.) (The docs have been corrected, see comments below)
I don't like catching exceptions to detect an expected (non-exceptional) result. And besides, I don't actually want to load the stream, I just want to know whether it exists.
Is there a better way to do this, perhaps with lower-level resource APIs -- ideally without actually loading the stream and without catching an exception?
I've found a solution that I'm using which doesn't work directly with a pack Uri but instead looks up a resource by it's resource path. That being said, this example could be modified pretty easily to support a pack URI instead by just tacking on the resource path to the end of a uri which uses the Assembly to formulate the base part of the URI.
public static bool ResourceExists(string resourcePath)
{
var assembly = Assembly.GetExecutingAssembly();
return ResourceExists(assembly, resourcePath);
}
public static bool ResourceExists(Assembly assembly, string resourcePath)
{
return GetResourcePaths(assembly)
.Contains(resourcePath.ToLowerInvariant());
}
public static IEnumerable<object> GetResourcePaths(Assembly assembly)
{
var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
var resourceName = assembly.GetName().Name + ".g";
var resourceManager = new ResourceManager(resourceName, assembly);
try
{
var resourceSet = resourceManager.GetResourceSet(culture, true, true);
foreach(System.Collections.DictionaryEntry resource in resourceSet)
{
yield return resource.Key;
}
}
finally
{
resourceManager.ReleaseAllResources();
}
}