HttpContext.Current is Null visiting website - httpcontext

Im having af Website where im storing a global variable with settings in the HttpContext.Current.Application object
Lately i got some errors because the HttpContext.Current returns null, how can that happen and i there some way to "restart" the application in code
I never get the error on debug/test
The code is :
public static Comito.CMS.Domain.Entity.Solution.Solution GetStoredSolution()
{
try
{
if (HttpContext.Current.Application["Solution"] == null)
{
Comito.CMS.Domain.Entity.Solution.Solution result = Comito.CMS.Helpers.Main.GetStoredSolutionFromConfig();
if (result != null)
{
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["Solution"] = result;
HttpContext.Current.Application.UnLock();
}
else
HttpContext.Current.Response.Redirect("http://www.comito.dk");
return result;
}
object tmpSolution = HttpContext.Current.Application["Solution"];
if (tmpSolution != null)
{
if (tmpSolution.GetType() == typeof(Comito.CMS.Domain.Entity.Solution.Solution))
return (Comito.CMS.Domain.Entity.Solution.Solution)tmpSolution;
}
else
return Comito.CMS.Helpers.Main.GetStoredSolutionFromConfig();
return null;
}
catch (Exception ex)
{
return null;
}
}

Related

org.apache.fop.fo.flow.ExternalGraphic catches and logs ImageException I want to handle myself

I am transforming an Image into pdf for test purposes.
To ensure that the Image is compatible with the printing process later on, I'm running a quick test print during the upload.
I'm creating a simple Test-PDF with a transformer. When I try to print an image with an incompatible format, the ImageManager of the transformer throws an ImageException, starting in the preloadImage() function:
public ImageInfo preloadImage(String uri, Source src)
throws ImageException, IOException {
Iterator iter = registry.getPreloaderIterator();
while (iter.hasNext()) {
ImagePreloader preloader = (ImagePreloader)iter.next();
ImageInfo info = preloader.preloadImage(uri, src, imageContext);
if (info != null) {
return info;
}
}
throw new ImageException("The file format is not supported. No ImagePreloader found for "
+ uri);
}
throwing it to:
public ImageInfo needImageInfo(String uri, ImageSessionContext session, ImageManager manager)
throws ImageException, IOException {
//Fetch unique version of the URI and use it for synchronization so we have some sort of
//"row-level" locking instead of "table-level" locking (to use a database analogy).
//The fine locking strategy is necessary since preloading an image is a potentially long
//operation.
if (isInvalidURI(uri)) {
throw new FileNotFoundException("Image not found: " + uri);
}
String lockURI = uri.intern();
synchronized (lockURI) {
ImageInfo info = getImageInfo(uri);
if (info == null) {
try {
Source src = session.needSource(uri);
if (src == null) {
registerInvalidURI(uri);
throw new FileNotFoundException("Image not found: " + uri);
}
info = manager.preloadImage(uri, src);
session.returnSource(uri, src);
} catch (IOException ioe) {
registerInvalidURI(uri);
throw ioe;
} catch (ImageException e) {
registerInvalidURI(uri);
throw e;
}
putImageInfo(info);
}
return info;
}
}
throwing it to :
public ImageInfo getImageInfo(String uri, ImageSessionContext session)
throws ImageException, IOException {
if (getCache() != null) {
return getCache().needImageInfo(uri, session, this);
} else {
return preloadImage(uri, session);
}
}
Finally it gets caught and logged in the ExternalGraphic.class:
/** {#inheritDoc} */
public void bind(PropertyList pList) throws FOPException {
super.bind(pList);
src = pList.get(PR_SRC).getString();
//Additional processing: obtain the image's intrinsic size and baseline information
url = URISpecification.getURL(src);
FOUserAgent userAgent = getUserAgent();
ImageManager manager = userAgent.getFactory().getImageManager();
ImageInfo info = null;
try {
info = manager.getImageInfo(url, userAgent.getImageSessionContext());
} catch (ImageException e) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageError(this, url, e, getLocator());
} catch (FileNotFoundException fnfe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageNotFound(this, url, fnfe, getLocator());
} catch (IOException ioe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageIOError(this, url, ioe, getLocator());
}
if (info != null) {
this.intrinsicWidth = info.getSize().getWidthMpt();
this.intrinsicHeight = info.getSize().getHeightMpt();
int baseline = info.getSize().getBaselinePositionFromBottom();
if (baseline != 0) {
this.intrinsicAlignmentAdjust
= FixedLength.getInstance(-baseline);
}
}
}
That way it isn't accessible for me in my code that uses the transformer.
I tried to use a custom ErrorListener, but the transformer only registers fatalErrors to the ErrorListener.
Is there any way to access the Exception and handle it myself without changing the code of the library?
It was easier than I thought. Before I call the transformation I register a costum EventListener to the User Agent of the Fop I'm using. This Listener just stores the Information what kind of Event was triggered, so I can throw an Exception if it's an ImageError.
My Listener:
import org.apache.fop.events.Event;
import org.apache.fop.events.EventListener;
public class ImageErrorListener implements EventListener
{
private String eventKey = "";
private boolean imageError = false;
#Override
public void processEvent(Event event)
{
eventKey = event.getEventKey();
if(eventKey.equals("imageError")) {
imageError = true;
}
}
public String getEventKey()
{
return eventKey;
}
public void setEventKey(String eventKey)
{
this.eventKey = eventKey;
}
public boolean isImageError()
{
return imageError;
}
public void setImageError(boolean imageError)
{
this.imageError = imageError;
}
}
Use of the Listener:
// Start XSLT transformation and FOP processing
ImageErrorListener imageListener = new ImageErrorListener();
fop.getUserAgent().getEventBroadcaster().addEventListener(imageListener);
if (res != null)
{
transformer.transform(xmlDomStreamSource, res);
}
if(imageListener.isImageError()) {
throw new ImageException("");
}
fop is of the type Fop ,xmlDomStreamSource ist the xml-Source I want to transform and res is my SAXResult.

Not all code paths return value while using Try Catch

I have been getting "not all code paths return value" in the following code. I have the code below. I think I am returning appropriately but still there is an error.
[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
try
{
Employee incomingEmployee = employee;
if (incomingEmployee == null)
{
Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
}
else if (UserManager.AddUser(employee) > 0)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
You forgot a return statement in the first if statement.
[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
try
{
Employee incomingEmployee = employee;
if (incomingEmployee == null)
{
-->return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
}
else if (UserManager.AddUser(employee) > 0)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}

Why is Entity Framework inserting duplicating records into table

For some reason .Net Entity Framework is inserting multiple duplicate records into a table called groups in my database. It seems to be occurring when a user logs in and access group index page.
Here are code snippets of my Index page controller code, as well as the DataContext get method and update method for Groups.
I'm not seeing whats wrong here as I'm only building a model and returning it to Index view. Anyone have any suggestions? I'm using MVC 4, Entity Framework 6.
Screenshot of records: It goes on for 50 rows like this.
Index View Controller
[Authorize(Roles = "Standard, Administrator")]
public ActionResult Index()
{
int _userId = WebSecurity.CurrentUserId;
var model = new GroupIndexModel();
if (Roles.GetRolesForUser().Contains("Administrator"))
{
ViewBag.Role = "Administrator";
var modelList = model.BuildIndexModel(_ctx.Groups.GetAllGroups());
modelList.CampaignTemplates = _ctx.Templates.GetAllCampaignTemplateList();
modelList.ProcedureTemplates = _ctx.Templates.GetAllProcedureTemplateList();
return View(modelList);
}
else
{
ViewBag.Role = "Standard";
var userGroups = _ctx.ManyToManyRelationShips.GetUserGroups(_userId);
var modelList = model.BuildIndexModel(_ctx.ManyToManyRelationShips.GetGroupsEntitiesForUser(userGroups));
foreach( var group in modelList.GroupObjects)
{
modelList.CampaignTemplates = _ctx.Templates.GetAllCampaignTemplateList().FindAll(p => p.GroupID == group.GroupId);
}
var tempProcTemplateList = _ctx.Templates.GetAllProcedureTemplateList();
foreach (var cTemplate in modelList.CampaignTemplates)
{
modelList.ProcedureTemplates.AddRange(tempProcTemplateList.FindAll(p => p.CampaignTemplateID == cTemplate.CampaignTemplateId));
}
return View(modelList);
}
}
Groups Manager (Get, GetAll, Add, Update Functions)
public Group Get(int groupId)
{
try
{
var group = new Group();
var temp = _ctx.Groups.First(p => p.GroupId == groupId);
if (temp != null)
{
group.GroupId = temp.GroupId;
group.CompanyName = temp.CompanyName;
group.Email = temp.Email;
group.PhoneNumber = temp.PhoneNumber;
group.CreatedDate = temp.CreatedDate;
group.LastModifiedDate = temp.LastModifiedDate;
}
return group;
}
catch (Exception ex)
{
logger.Error("An Error occured getting a group", ex);
// Console.WriteLine("An Error occured getting a group" + System.Environment.NewLine + ex);
return null;
}
}
public List<Group> GetAllGroups()
{
try
{
var groupList = _ctx.Groups.OrderBy(p => p.CompanyName).ToList<Group>();
return groupList;
}
catch (Exception ex)
{
logger.Error("An Error occured getting groups", ex);
//Console.WriteLine("An Error occured getting groups" + System.Environment.NewLine + ex);
return null;
}
}
public int Add(Group eGroup)
{
int newGroupId;
try
{
_ctx.Groups.Add(eGroup);
_ctx.SaveChanges();
newGroupId = eGroup.GroupId;
return newGroupId;
}
catch (Exception ex)
{
logger.Error("An Error occured adding group", ex);
//Console.WriteLine("An Error occured adding group" + System.Environment.NewLine + ex);
return -1;
}
}
public void UpdateGroup(Group eGroup)
{
try
{
var updev = _ctx.Groups.First(p => p.GroupId == eGroup.GroupId);
if (updev.CompanyName != eGroup.CompanyName)
updev.CompanyName = eGroup.CompanyName;
if (updev.Email != eGroup.Email)
updev.Email = eGroup.Email;
if (updev.PhoneNumber != eGroup.PhoneNumber)
updev.PhoneNumber = eGroup.PhoneNumber;
updev.LastModifiedDate = DateTime.Now;
_ctx.SaveChanges();
}
catch (Exception ex)
{
logger.Error("An Error occured updating group", ex);
// Console.WriteLine("An Error occured updating group" + System.Environment.NewLine + ex);
return;
}
}

Having Trouble with ObjectInputStream/OutputStream

I am having trouble with my programs ability to save my Maps to a file. Here are my two methods for writing and reading my maps and arraylist.
Here is my read method:
private void getData() throws IOException, ClassNotFoundException {
File f_Instructors = new File(PSLTrackerInfo.file + "instructors.brent");
File f_Students = new File(PSLTrackerInfo.file + "students.brent");
File f_Times = new File(PSLTrackerInfo.file + "times.brent");
if (f_Instructors.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Instructors)))) {
//Add theList back in
if (in.readObject() != null) {
TreeMap<Instructor, Set<Student>> read = null;
while(in.available() > 0) {
read = (TreeMap<Instructor, Set<Student>>)
in.readObject();
}
if (read != null) {
for (Instructor key : read.keySet()) {
System.out.println(key);
Set<Student> values = read.get(key);
PSLTrackerInfo.addInstructor(key, values);
}
System.out.println("Instructors Found! Reading...");
} else {
System.out.println("No instructor data saved.1");
}
} else {
System.out.println("No instructor data saved.2");
}
in.close();
}
}
//Add times back in
if (f_Times.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Times)))) {
if (in.readObject() != null) {
TreeMap<Student, ArrayList<Date>> readTimes = null;
while(in.available() > 0) {
readTimes = (TreeMap<Student, ArrayList<Date>>) in.readObject();
}
if (readTimes != null) {
for (Student key : readTimes.keySet()) {
System.out.println(key);
ArrayList<Date> values = readTimes.get(key);
PSLTrackerInfo.addTimes(key, values);
}
System.out.println("Dates Found! Reading...");
} else {
System.out.println("No dates saved.");
}
} else {
System.out.println("No dates saved.");
}
in.close();
}
}
//Add newStudents back in
if (f_Students.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Students)))) {
if (in.readObject() != null) {
ArrayList<Student> readStudents = null;
while (in.available() > 0) {
readStudents = (ArrayList<Student>) in.readObject();
}
if (readStudents != null) {
PSLTrackerInfo.setTheList(readStudents);
}
System.out.println("New students found! Reading...");
} else {
System.out.println("No new students data saved.");
}
in.close();
}
}
}
And Here is my Writing method:
private void saveData() {
System.out.println("Saving Data...");
File f_Instructors = new File(PSLTrackerInfo.file + "instructors.brent");
File f_Students = new File(PSLTrackerInfo.file + "students.brent");
File f_Times = new File(PSLTrackerInfo.file + "times.brent");
ObjectOutputStream out_Instructors = null;
ObjectOutputStream out_Students = null;
ObjectOutputStream out_Times = null;
try {
out_Instructors = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Instructors)));
out_Students = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Students)));
out_Times = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Times)));
out_Instructors.writeObject(PSLTrackerInfo.getMap());
out_Times.writeObject(PSLTrackerInfo.getTimes());
out_Students.writeObject(PSLTrackerInfo.getList());
out_Instructors.flush();
out_Students.flush();
out_Times.flush();
out_Instructors.close();
out_Students.close();
out_Times.close();
} catch (IOException ex) {
Logger.getLogger(PrivateLessonsTrackerGUI.class.getName())
.log(Level.SEVERE, null, ex);
}
System.exit(0);
}
Sorry if it is a little confusing I have 3 files to save 3 different objects, if there is a way to save it into one file let me know but I just was getting a lot of errors that I couldn't figure out how to solve so this is what I ended up doing. Thanks for any help given.
To EJP: I tried this
TreeMap<Instructor, Set<Student>> read = null;
try {
read = (TreeMap<Instructor, Set<Student>>)
in.readObject();
} catch (EOFException e) {
System.out.println("Caught EOFException!");
}
And even when there was data in it when it was written to the file, I got an EOFException everytime.
readObject() doesn't return null unless you wrote a null. If you're using that as a test for end of stream, it is invalid. The correct technique is to catch EOFException.
You are calling it and throwing away the result if it isn't null, and then calling it again. The second call will throw EOFException if there isn't another object in the file. It won't give you the same result as the first call. It's a stream.
available() is also not a valid test for end of stream. That's not what it's for. See the Javadoc. Again, the correct technique with readObject() is to catch EOFException.

How can I change message in DuplexSessionChannel (tcpTransport) in WCF custom channel?

I implement IDuplexSessionChannel on my Custom Channel because I use tcpTransport. In that custom channel, I cache service call response(client side caching). But it has errors. In IRequestChannel it works fine. How can I change message in TryMessage method. My code :
public Message Receive(TimeSpan timeout)
{
Message response = null;
response = CommunicationCacheManager.Get(_request.Headers.Action, _request);
if (response == null)
{
response = this.InnerChannel.Receive(timeout);
int cacheTimeout = 0;
if (response.Headers.FindHeader(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE) > -1)
{
cacheTimeout = response.Headers.GetHeader<int>(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE);
}
if (cacheTimeout > 0 && response != null &&
!response.IsFault &&
!response.IsEmpty)
{
CommunicationCacheManager.Add(_request.Headers.Action, cacheTimeout, ref response);
}
}
return response;
}
public Message Receive()
{
return this.InnerChannel.Receive();
}
public bool TryReceive(TimeSpan timeout, out Message message)
{
ThrowIfDisposedOrNotOpen();
message = null;
bool timedout = false;
try
{
message = this.Receive(timeout);
}
catch (TimeoutException)
{
timedout = true;
}
return (!timedout);
}
CacheManager works. And I get the response Cache. But tryReceive run again and when I look Message. Message is closed. How can I fix that
Problem is solved.
Tcp Binding add RelatesTo Header to Message. So code is changed to
public Message Receive(TimeSpan timeout)
{
Message response = null;
response = CommunicationCacheManager.Get(_request.Headers.Action, _request);
if (response == null)
{
response = this.InnerChannel.Receive(timeout);
int cacheTimeout = 0;
if (response.Headers.FindHeader(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE) > -1)
{
cacheTimeout = response.Headers.GetHeader<int>(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE);
}
if (cacheTimeout > 0 && response != null &&
!response.IsFault &&
!response.IsEmpty)
{
CommunicationCacheManager.Add(_request.Headers.Action, cacheTimeout, ref response);
}
}
else
{
response.Headers.RelatesTo=_request.Header.MessageId;
}
return response;
}