eventlog not working in an asp.net application - asp.net

from an ASP.Net 3.5 web application, I'm trying to log messages to the Windows EventLog.
I first tried with the EntLib Logginh block, but when this failed I tried with the EventLog class directly. It failed too. They do not throw any exception... the just don't write the message. EntLib did write the message to a file, but not to the Windows EventLog.
Here is my code:
public static void LogMessage(string title, string message){
//EventLog log = new EventLog();
//log.Source = LOG_SOURCE;
//log.WriteEntry(message, EventLogEntryType.Error);
//EventLog.WriteEntry(LOG_SOURCE, message);
LogWriter writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
writer.Write(message);
}
I create the log & source in an installer class. Let me know if I should place that code here. The log is created correctly, since I can see it in the EventViewer. The source is created correctly, since I can see it in the "EventLog\MyLog" folder at the regedit.
I've been reading and there is an article stating following line could help:
EventLogPermission perm = new EventLogPermission(EventLogPermissionAccess.Administer, ".");
perm.PermitOnly();
but it didn't.
If it helps, my code structure is as follows:
Class library project (here is the LogMessage method)
Class Library project (here are the methods which catch exceptions and call LogMessage)
ASP Net web application project (web pages. This layer calls layer #2. Here is my installer class too)
Web setup project (this has custom actions pointing to web setup project output)
Could you please help to figure out what's happening???
Thanks
I found the following resource: "http://www.netframeworkdev.com/net-base-class-library/trouble-writing-to-eventlog-16723.shtml", so it seems it is not possibly to create custom logs from ASP... still investigating

Try giving the Network Service account the appropriate permissions

Related

Enterprise Library not logging in setup project

I need your opinion on this: Is it possible to use enterprise library logging dll in the setup project?
Here's what I did:
I created a setup project which will call a windows form to install the database. When I installed the project, it did call the windows form. However, when I click on the "Install" button, it seems that there's a problem and I don't know where it is. Then another popup message is displayed which said that it cannot locate the logging configuration.
But the config file for the windows form is there which includes the configuration for the logging dll. I don't have any idea where to look into.
Please help me with this?
Below is the error message:
UPDATE
I observed that when I run the exe file as is, the enterprise library logging config works. But with the setup project, it does not look for it. Any help on this?
Below is the code for this:
[RunInstaller(true)]
public partial class IPWInstaller : Installer
{
public IPWInstaller()
{
InitializeComponent();
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
string targetPath = Context.Parameters["TargetDir"];
InstallDatabase db = new InstallDatabase(targetPath);
DialogResult dbResult = db.ShowDialog();
if (dbResult != DialogResult.OK)
{
throw new InstallException("Database is not installed.");
}
ConfigureFiles config = new ConfigureFiles(targetPath);
DialogResult configResult = config.ShowDialog();
if (configResult != DialogResult.OK)
{
throw new InstallException("Config files are not saved correctly.");
}
}
}
LATEST UPDATE:
I tried to set the value of a certain configuration to my messagebox. This is the result of it when I run the install project.
Is there a way to call my app.config in the setup project
There are at least a couple of things that can go wrong.
The app is not running as it would if you ran it as an interactive user. It is being called from an msiexec.exe process that knows nothing about your intended environment, such as working directory. None of the automatic things that happen because you run from an explorer shell will happen. Any paths you use need to be full and explicit. I think you may need to explicitly load your settings file.
Something else that can happen in a per machine install is that custom actions run with the system account so any code which assumes you have access to databases, user profile items like folders can fail.
Another problem is that Windows Forms often don't work well when called from a VS custom action. It's not something that works very well because that environment is not the STA threading model that is required for window messages etc.
In general it's better to run these config programs after the install the first time the app starts because then you are in a normal environment, debugging and testing is straightforward, and if the db gets lost the user could run the program again to recreate it instead of uninstalling and reinstalling the setup.

Error when webservice file included in my project

In my project, I included Webservice files, when I tried to run, I got this error in Chrome browser.
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0029: Cannot implicitly convert type 'Unified.WebService.GetOrder [c:\Users\Venkatesh\AppData\Local\Temp\Temporary ASP.NET Files\root\417f2571\29df25a\assembly\dl3\1f05470e\0779ccf4_47dfcd01_0\WasteManagement.DLL]' to 'Unified.WebService.GetOrder [c:\Users\Venkatesh\Desktop\Venkateshwar\Company Related\Waste Management - Copy\WasteManagement\WasteManagement\App_Code\GetOrder.cs(8)]'
Source Error:
Line 43: public GetOrder retrieveOrder(string orderNumber)
Line 44: {
//Calling Web service method in my class
Line 45:/*ERROR*/ return connection.getOrder(orderNumber);
Line 46: }
Line 47:
When I clicked Compiler Warning Messages, it is showing error in all the connections which were through Web service.
If necessary, I will share the code too. (As I am new to asp.net, I cant understand which part of code to share. So, please mention which part of code you want, if needed.)
Your Web-service should be independent project in your solution. After that you should add Web Reference for it, and after that you can safely call it.
Web Service is not a basic class you cann add and use - it is a different thing, so you can't simply add it to your App_Code folder to make it work.
From MSDN:
Web service discovery is the process by which a client locates a Web service and obtains its service description. The process of Web service discovery in Visual Studio involves interrogating a Web site following a predetermined algorithm. The goal of the process is to locate the service description, which is an XML document that uses the Web Services Description Language (WSDL).
The service description describes what services are available and how to interact with those services. Without a service description, it is impossible to programmatically interact with a Web service.
Edit:
Yes, you can remove [WebMethod] attributes, etc, from web service declaration, and temporary use it like class, but after that you still have to add a Web reference for it to use it like Web Service.

can't register objects using unity 2.0

I created a web service recently and am using unity to inject my object dependencies. My composition root is the Application_Start in the web services and am using the web.config to do my object to interface mappings. Everything was working fine, however after i loaded my project into tfs i keep getting an error stating that it cant resolve one of the interfaces. I removed the code to register my objects from the web.config and regsistered them in code instead to test and it all works fine. Any ideas what the problem is. Any ideas how i can troubleshoot this problem.
Before TFs :-
UnityContainer uContainer = new UnityContainer();
UnityConfigurationSection Section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
Section.Configure(uContainer, "CentralRepositoryContainer");
Application["uContainer"] = uContainer;
Amended code which works fine :-
UnityContainer uContainer = new UnityContainer();
uContainer.RegisterType<ICentralRepositoryLifeTimehelper, CentralRepositoryLifeTimeHelper>();
uContainer.RegisterType<IJobsHandler, JobsHandler>();
Application["uContainer"] = uContainer;
I don't know the problem, but to troubleshoot print out all the Unity containers registrations and see what's missing/changed.
Use the code sample from Retrieving Container Registration Information

How to do mocks for Web tests?

I want to write a few web tests (over WatiN/Selenium + CassiniDev web server) for my asp.net web application.
Problem I encountered is that I dont know what to do in such situations:
there is a page where user can click the button to call some third-party service. In my web test i want to create mock of this service, which will always return static value (some value in these test case and other value in other test case).
How can i do that?
Currently i use IoC/DI container Microsoft Unity. And my pages gets his dependencies in a manner described in http://msdn.microsoft.com/en-us/library/ff664622%28v=pandp.50%29.aspx.
The only solution that comes to my head is: place all dependencies in web.config for each test case and copy necessary web.config on SetUp of test. This solution completly painful!
Any ideas?
I use WatiN and Cassini-dev in my integration tests as well and have had to deal with similar issues. In my setup fixture I deploy my Asp.Net web application to a temporary folder in my test folder which allows me to play around with the configuration before starting up cassini-dev. I use Windsor for my CI which allows me to change injected components at the configuration level. You may also be able to acheive this with Unity.
If the service you are referring to is a web service you just mock out a web service using the interface you have been coding to.
Here are the steps that I take when running my integration tests:
Create a temp web directory
Publish the Asp.Net web application to the temp directory (I use MSBuild to do this)
Deploy temp database (Using MSbuild and database projects but could be done a number of ways)
Deploy temp membership database (see my blog post on how to do this in code)
Update the web.config of the deployed Asp.Net web application to point to the temp databases and change any other settings relevant for testing.
Start up the website using Cassini-Dev. I also hit the site with a http request so that I can verify the site is up before running any tests.
Run the tests.
After running the tests you should clean up.
Stop cassini-dev
Delete the temp hosting folder
Delete the temp databases. I use Sql server SMO objects that allow me to query the Sql Server which I use to delete up any old databases that have been left lying around after any previously failed test runs.
How to deploy a website using MSbuild in code
var properties = new Dictionary<string, string>
{
{"Configuration", isDebug ? "Debug" : "Release"},
{"WebProjectOutputDir", tempHostingDirectory.FullName},
{"DeployToDatabase", "true"},
{"OutDir", Path.Combine(tempHostingDirectory.FullName, "bin\\")}
};
using (var engine = new ProjectCollection(properties))
{
engine
.LoadProject(<web project path>, "4.0")
.Build(new[] {"Build", "ResolveReferences", "_CopyWebApplication"});
}
Unity configuration section usage: http://www.pnpguidance.net/Post/UnityContainerUnityConfigurationSectionAppConfigWebConfig.aspx
Generating asp.net membership database in code: http://bronumski.blogspot.com/2011/06/generating-creating-aspnet-application.html
Msbuild ProjectCollection on MSDN: http://msdn.microsoft.com/en-us/library/microsoft.build.evaluation.projectcollection.aspx
It sounds like you are trying to mock a web service.
Web services usually inherit from MarshalByRefObject, this means you can create a mock by inheriting from RealProxy to create a transparent proxy that pretends to be the webservice:
class Mock : RealProxy
{
public Mock()
: base(typeof(IStuff)) { }
public IStuff GetStuff()
{
return (IStuff)GetTransparentProxy();
}
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage message = (IMethodCallMessage)msg;
// the message object provides the MethodInfo that was called
// as well as the arguments.
// <Insert logic here>
return new ReturnMessage(new NotImplementedException("comming soon to a test near you ..."), message);
}
}
I belieave NMock2 uses RealProxy for it's mocks, so you should be able to use it to mock the web service instead.

Registering a .NET DLL for COM visibility in ASP Classic

We're trying to write a couple of applications. One ASP.NET site uses the .NET Assembly xxx.Elements.dll, which provides utility functions.
The other, a Classic ASP site, should also use the same DLL in order to use the same utility functions. (It will be used for encrypting data between the two sites).
Despite many attemps and Googling, we cannot get this working.
We have:
Applied ComVisibility to the Assembly.info and ensured there is a Guid:
[assembly: ComVisible(true)]
[assembly: Guid("ab96fbc3-aa39-4fb6-8628-13778445e503")]
We made sure our type ticks the boxes on type visibility by ensuring it has a default constructor, is ComVisible and has a Guid. We've also created a simplistic method for testing:
namespace xxx.Elements
{
[GuidAttribute("D3BE2C7D-7550-4da1-8F61-6871E193242F")]
[ComVisible(true)]
public class UrlUtility : IUrlUtility
{
public UrlUtility()
{
}
public string Test()
{
return "HellO";
}
}
}
Using the interface:
[GuidAttribute("D3BE2C7D-7550-4da1-8F61-6871E193242A")]
[ComVisible(true)]
public interface IUrlUtility
{
string Test();
}
We found this really useful (though non-resolving) post here to do this: warning MSB3391: does not contain any types that can be unregistered for COM Interop.
We have also checked the Regsiter for COM-Interop in the Project property pages.
This continues to output the warning:
c:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(3341,9): warning MSB3214: "D:\dev\yyy\xxx.Elements\bin\Release\xxx.Elements.dll" does not contain any types that can be registered for COM Interop.
when compiling. If we run REGASM xxx.Elements.dll /tlb directly, we get:
Microsoft (R) .NET Framework Assembly Registration Utility 4.0.30319.1
Copyright (C) Microsoft Corporation 1998-2004. All rights reserved.
Types registered successfully
Assembly exported to 'D:\dev\yyy\IWW.Elements\bin\release\xxx.eleme
nts.tlb', and the type library was registered successfully
So a little confused about the ambiguity.
When we look in the registry, it does appear to register the .tlb correctly:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\TypeLib\{AB96FBC3-AA39-4FB6-8628-13778445E503}]
[HKEY_CLASSES_ROOT\TypeLib\{AB96FBC3-AA39-4FB6-8628-13778445E503}\1.1]
#="Elementary support library for xxx' products"
[HKEY_CLASSES_ROOT\TypeLib\{AB96FBC3-AA39-4FB6-8628-13778445E503}\1.1\0]
[HKEY_CLASSES_ROOT\TypeLib\{AB96FBC3-AA39-4FB6-8628-13778445E503}\1.1\0\win32]
#="D:\\dev\\yyy\\xxx.Elements\\bin\\Release\\xxx.Elements.tlb"
[HKEY_CLASSES_ROOT\TypeLib\{AB96FBC3-AA39-4FB6-8628-13778445E503}\1.1\FLAGS]
#="0"
[HKEY_CLASSES_ROOT\TypeLib\{AB96FBC3-AA39-4FB6-8628-13778445E503}\1.1\HELPDIR]
#="D:\\dev\\yyy\\xxx.Elements\\bin\\Release"
We have also registered the type in the GAC:
gacutil /i xxx.Elements.dll
and given it a strong name using:
sn -k xxx.Elements.snk
and included the name in the AssemblyInfo.cs file:
[assembly: AssemblyKeyFile(#"D:\dev\yyy\xxx.Elements\xxx.Elements.key")]
We have also applied the IUSR user Read permission to the registry keys:
HKEY_CLASSES_ROOT\TypeLib\{AB96FBC3-AA39-4FB6-8628-13778445E503}
HKEY_USERS\S-1-5-20\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones
(the last one was suggested here: Cannot instanciate .Net COM object in classic ASP/VBScript page (Error ASP 0177))
Despite all this, when we activate the object in the ASP page using the code:
dim urlUtility
set urlUtility = Server.CreateObject("xxx.Elements.UrlUtility")
' should return "Hello"
test=urlUtility.Test()
The process stops and when we debug into the W3WP process, we get the error:
Server object: 006~ASP 0177~Server.CreateObject Failed~800401f3
We have tried to check all the boxes, but we must be missing something. Any ideas, please?
I had a similar problem some time ago. I solved it by hosting the .NET component in the COM+ application server. This article suggests and describes the same. In addition to the article it maybe necessary to configure your assembly (It is running stand-alone, if you do as suggested). In this case you need a manifest and a config file in the applications root. Look at this SO answer for details.

Resources