I need to run a .net C# application (developed on a Windows system) as a service/daemon on an embedded system with a minimal Ubuntu installation (no X, no servers except ssh, only relevant software). I created an /etc/init.d script containing the line
mono-service my-.net-app.exe service
and this worked well. There is also an option to start the application interactively (for debugging purposes) with
mono my-.net-app.exe interactive
The last argument is an argument for the .NET application telling it if it's running as service. This was implemented roughly this way:
private static void Main(string[] args){
if(args.Any() && args[0] != null && args[0] == "service"){
ServiceBase.Run(new[] {(ServiceBase) new MyService()});
}else{
try{
Console.Write("starting app");
if(StartWork()){
Console.Write("press any key to exit");
Console.ReadKey();
}else{
Console.WriteLine("starting app failed");
}
} // end try
finally{
StopWork();
Console.WriteLine("finished app");
}
} // end else
...
} // end Main
public class MyService : ServiceBase{
static private Thread _worker;
protected override void OnStart(string[] args){
_worker = new Thread(() => Program.StartWork(asService: true)); // this asService tells StartWork to not produce console output
_worker.Start();
}
protected override void OnStop(){
Program.StopWork();
_worker.Join(1000);
}
}
The purpose of this implementation was to allow the application to die gracefully (i.e. to execute StopWork()) upon sending SIGTERM on the linux machine.
For security reasons, I need to be able to run the service as non-root. I created a new user and made it owner of the directories where the application writes its log files and added it to various groups to give it access to required device files. Then, root would start the application as
sudo -u newuser mono-service my-.net-app.exe service
or
sudo -u newuser mono my-.net-app.exe interactive
The second option with mono works well, but the first one with mono-service doesn't (see error message below). Since it works with mono, I'm confident that the user newuser has appropriate rights to access all relevant files and devices. I wonder whether mono-service has been conceived as a root-only application.
I could also live with using the mono option and suppressing the console output, like this:
private static void Main(string[] args){
try{
Console.Write("starting app");
if(StartWork(consoleoutput)){ // true or false depending on whether the service argument was given
Console.Write("press any key to exit");
Console.ReadKey();
}else{
Console.WriteLine("starting app failed");
}
} // end try
finally{
StopWork();
Console.WriteLine("finished app");
}
...
} // end Main
but then, when I kill the service (i.e. send SIGTERM to the mono process), it stops the .net application immediately without allowing it to execute the finally block.
Finally, my question is whether someone has an idea why mono-service is failing when not started as root. The error message is the following and, as I mentioned before, it doesn't exist when I use mono instead of mono-service.
ERROR Program [4] [15:03:06.795 01/12/14] Error in Main!
FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
---> NHibernate.HibernateException: Could not create the driver from SAFEmine.DataStore.Database.MonoSqliteDriver, SAFEmine.DataStore, Version=1.3.0.6, Culture=neutral, PublicKeyToken=null. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> NHibernate.HibernateException: The IDbCommand and IDbConnection implementation in the assembly Mono.Data.Sqlite could not be found. Ensure that the assembly Mono.Data.Sqlite is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use <qualifyAssembly/> element in the application configuration file to specify the full name of the assembly.
at NHibernate.Driver.ReflectionBasedDriver..ctor (System.String providerInvariantName, System.String driverAssemblyName, System.String connectionTypeName, System.String commandTypeName) [0x00000] in <filename unknown>:0
at NHibernate.Driver.ReflectionBasedDriver..ctor (System.String driverAssemblyName, System.String connectionTypeName, System.String commandTypeName) [0x00000] in <filename unknown>:0
at SAFEmine.DataStore.Database.MonoSqliteDriver..ctor () [0x00000] in <filename unknown>:0
at (wrapper managed-to-native) System.Reflection.MonoCMethod:InternalInvoke (System.Reflection.MonoCMethod,object,object[],System.Exception&)
at System.Reflection.MonoCMethod.InternalInvoke (System.Object obj, System.Object[] parameters) [0x00000] in <filename unknown>:0
Alternatively, if I settle for mono instead of mono-service, is there a way to catch a SIGTERM from within the .net application and to die gracefully? I tried this: https://github.com/ServiceStack/ServiceStack/wiki/Run-ServiceStack-as-a-daemon-on-Linux , but the code wouldn't compile on Visual Studio saying that the using Mono.Unix; and using Mono.Unix.Native lines were invalid. I also installed Mono on Windows and tried to use the Mono compiler, but it complained about the same thing.
The mono-service.exe creates a new AppDomain with ApplicationBase being the current directory. This might influence assembly loading. Since you are seeing such an error, I would try to enable MONO_LOG_LEVEL=debug MONO_LOG_MASK=asm and/or strace -e file to see if they provide any hints.
Also note that you can pass -d switch to mono-service to have it change directory for you.
Related
Scenario:
I have hooked up the Web job with a CancellationToken and need to simulate shutdown to see if the cancellation is being processed successfully. I've tried the Ctrl + C combination but the cancellation did not fire. What is the correct way of simulating this shutdown for debugging purposes?
Since this is debug code, did it with a bit of a hack. The issue in my case is, the CancellationToken was being passed by a framework call and did not allow access to the CancellationTokenSource.
private async Task InitializeEventProcessing(CancellationToken ctx)
{
#if DEBUG
CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
ctx = cts.Token;
#endif
.
.
.
}
Didn't really like the other answer, so here is what I did...
The built in WebJobsShutdownWatcher looks for an environment variable WEBJOBS_SHUTDOWN_FILE and watches for changes.
If you configure the debug settings to provide a file name for that environment variable, then all you have to do create that file(contents don't matter) and it will follow the same shutdown path as if it is deployed.
Of course you have to delete it afterward, or add a build step to delete it on debug or something, but at least it's executing the same code as graceful shutdown on the host.
I'm attempting to follow the instructions to install the windows service host using NServiceBus.Host.exe for the VideoStore sample app. I'm following the instructions from the web site.
My application runs fine when doing an F5 session in Visual Studio. It's hosting using the console app mode for the host. When I attempt to use the command line to perform the installation, I get multiple errors.
The command line I'm running is:
NServiceBus.Host.exe /install /serviceName:"VideoStore.Sales"
/displayName:"VideoStore.Sales" /description:"Endpoint for
VideoStore.Sales"
/endpointConfigurationType:"VideoStore.Sales.EndpointConfig,
VideoStore.Sales" /username:".\MySvc" /password:"MyPassword"
NServiceBus.Production
Running this resulted in the following exception:
Initializing the installer in the Install AppDomain
Unhandled Exception: System.InvalidOperationException: Sequence
contains more than one matching element at
System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source,
Func2 predicate) at
System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext() at
System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at
NServiceBus.Hosting.Profiles.ProfileManager..ctor(List1
assembliesToScan, IConfigureThisEndpoint specifier, String[] args,
List`1 defaultProfiles)
It turns out, this error is caused because my application is referencing both the NServiceBus.Host assembly as well as the NServiceBus.Hosting.Azure assembly. This is because my application is being deployed both in a Windows environment as well as to an Azure worker role. I can switch between the azure emulator and the console-mode for worker roles without issue simply by changing which projects i'm starting when debugging. (Azure cloud service project vs each of the worker projects.)
I was able to resolve this by deleting the NServiceBus.Hosting.Azure.dll assembly to prevent the assembly scanning from finding it. IMHO, this is a bug. Either allow me to specify the host type explicitly or handle a scenario where multiple types are found.
This stopped the previous exception, and instead introduced a new one:
Unhandled Exception:
System.Configuration.ConfigurationErrorsException: Command line
argument 'endpointConfigurationType' has specified to use the type
'VideoStore.Sales.EndpointConfig, VideoStore.Sales' but that type
could not be loaded. at
NServiceBus.Hosting.Windows.EndpointTypeDeterminer.TryGetEndpointConfigurationTypeFromArguments(HostArguments
arguments, Type& type) in y:\BuildAgent\work
\31f8c64a6e8a2d7c\src\NServiceBus.Hosting.Windows\EndpointTypeDeterminer.cs:line
101 at NServiceBus.Hosting.Windows.Program.Main(String[] args) in
y:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBus.Hosting.Windows\Program.cs:line
38
Both that type and that assembly exist. I've even verified that .NET is loading the type via enabling fusion loader logging:
The operation was successful. Bind result: hr = 0x0. The operation
completed successfully.
Assembly manager loaded from:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll Running under
executable
C:\Projects\Testing\NServiceBus.Azure.Samples-master\VideoStore.AzureServiceBus.Cloud\VideoStore.Sales\bin\Debug\NServiceBus.Host.exe
--- A detailed error log follows.
=== Pre-bind state information === LOG: DisplayName = VideoStore.Sales (Partial) WRN: Partial binding information was supplied for an
assembly: WRN: Assembly Name: VideoStore.Sales | Domain ID: 1 WRN: A
partial bind occurs when only part of the assembly display name is
provided. WRN: This might result in the binder loading an incorrect
assembly. WRN: It is recommended to provide a fully specified textual
identity for the assembly, WRN: that consists of the simple name,
version, culture, and public key token. WRN: See whitepaper
http://go.microsoft.com/fwlink/?LinkId=109270 for more information and
common solutions to this issue. LOG: Appbase =
file:///C:/Projects/Testing/NServiceBus.Azure.Samples-master/VideoStore.AzureServiceBus.Cloud/VideoStore.Sales/bin/Debug/
LOG: Initial PrivatePath = NULL LOG: Dynamic Base = NULL LOG: Cache
Base = NULL LOG: AppName = NServiceBus.Host.exe Calling assembly :
NServiceBus.Host, Version=4.6.0.0, Culture=neutral,
PublicKeyToken=9fc386479f8a226c.
What am I doing wrong here?
EDIT
I believe I see the issue. Basically, trying to avoid the first error where NServiceBus is resolving multiple Profiles due to the fact it's finding them in both NServiceBus.Core and NServicebus.Hosting.Azure is causing the second error.
This is because in order to load my EndpointConfig type, .NET also needs to load the NServicebus.Hosting.Azure assembly, as it implements AsA_Worker, which lives in NServiceBus.Hosting.Azure.
So be deleting that assembly, I'm preventing it from loading the EndpointConfig.
I'm still unclear as to how to resolve this. I need to get NServiceBus to stop scanning both hosting assemblies. This suggests that christof13's answer is correct, but I'm unable to get NServiceBus to ignore its own assemblies.
The root cause of this issue is that when NServiceBus enumerates profiles available, it scans all available assemblies and then does a LINQ statement to filter them down by type name.
The problem is that there are two NServiceBus.Production profiles, one defined in the NServiceBus.Host.dll, and one in the NServiceBus.Hosting.Azure assembly. Their type names are identical, and so the LINQ SingleOrDefault fails.
The suggestion to filter the assemblies searched wouldn't work because NServiceBus always loads its own assemblies. The filter only applies to my project's assemblies.
I was able to resolve this by creating a custom profile that doesn't have the same name as any other profile defined in any assemblies in my project. Something like:
public class DualCloudLocalProfile : IProfile {}
public class DualCloudLocalProfileHandler : IHandleProfile<DualCloudLocalProfile>
{
public void ProfileActivated()
{
if (LogManager.LoggerFactory is NullLoggerFactory || LogManager.LoggerFactory == null)
{
Configure.Instance.TraceLogger().ConsoleLogger();
}
}
}
public class CloudProfileLoggingHandler : IConfigureLoggingForProfile<DualCloudLocalProfile>
{
public void Configure(IConfigureThisEndpoint specifier)
{
//nothing for now
}
}
Once this was added into my project, I modified the install command to specify the new profile:
NServiceBus.Host.exe /install /serviceName:"VideoStore.Sales" /displayName:"VideoStore.Sales" /description:"Endpoint for VideoStore.Sales" /endpointConfigurationType:"VideoStore.Sales.EndpointConfig, VideoStore.Sales" /username:".\MySvc" /password:"MyPassword" VideoStore.Sales.DualCloudLocalProfile
This resolved the problem. I can now run the project as a cloud service and a NServiceBus.Host.exe hosted service, as well as deploy via the /install command for the host.
You can try to filter the assemblies with one the following methods
Configure.With(string probeDirectory)
Configure.With(params Assembly[] assemblies)
Configure.With(IEnumerable<Type> typesToScan)
By default I think that nservicebus scans all the assemblies in the folder, so if you filter with only the needed assemblies it will prevent from receiving this kind of error
http://docs.particular.net/nservicebus/the-nservicebus-host
I create HttpClient and call GetStringAsync method right at the button click handler:
var client = new HttpClient();
var response = await client.GetStringAsync("http://google.com");
Debug.WriteLine("Response received: {0}", response);
And every time I get the following error:
System.InvalidOperationException: Operation is not valid due to the current state of the object
2014-05-10 01:26:36.657 HelloWorld3[490:60b] Unhandled managed exception: Operation is not valid due to the current state of the object (System.InvalidOperationException)
at System.Lightup.Call[HttpWebRequest,Int64] (System.Delegate& storage, System.Net.HttpWebRequest instance, System.String methodName, Int64 parameter) [0x00000] in <filename unknown>:0
at System.Lightup.Set[HttpWebRequest,Int64] (System.Delegate& storage, System.Net.HttpWebRequest instance, System.String propertyName, Int64 value) [0x00000] in <filename unknown>:0
at System.Net.HttpWebRequestLightup.SetContentLength (System.Net.HttpWebRequest instance, Int64 value) [0x00000] in <filename unknown>:0
at System.Net.Http.HttpWebRequest.set_ContentLength (Int64 value) [0x00000] in <filename unknown>:0
at System.Net.Http.HttpClientHandler.StartRequest (System.Object obj) [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispat
chInfo.Throw () [0x0000b] in /Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:62
at System.Runtime.CompilerServices.TaskAwaiter`1[System.String].GetResult () [0x00000] in <filename unknown>:0
at HelloWorld3.MyViewController+<<ViewDidLoad>b__0>d__1.MoveNext () [0x00029] in c:\Sources\Local\HelloWorld3\HelloWorld3\MyViewController.cs:41
Debugging session ended.
The program 'Mono' has exited with code 0 (0x0).
I'm not using portable libs, nugets, etc. Just plain project created from a template.
How to solve this issue?
test project with reproduced issue here:
https://dl.dropboxusercontent.com/u/19503836/HelloWorld3.zip
In general this happens when you're building your application using PCL assemblies and from Windows.
I'm not using portable libs,
Ok, still you're likely falling into the same situation. You have the wrong (MS not XI) version of System.Http.Net.dll being copied (and compiled) on the Mac. E.g.
at System.Lightup....
Is not part of the assembly being shipped with Xamarin.iOS. Having this in your stack trace is an indication that the wrong assembly is being used.
This is a known issue that is being fixed (at least for the PCL part). In the mean time the general workaround is using a redirect file (see James blog) or build from the Mac.
In your specific case you might just need to ensure the right assembly is being referenced.
i had the same problem!
resolve with FlorianZimmermann solution.
on this link:
https://forums.xamarin.com/discussion/36713/issue-with-microsoft-http-net-library-operation-is-not-valid-due-to-the-current-state-of-the-objec
right-click on References directory for ios or android solution
select edit references
in packages tab , check System.Net.Http
build!
Hope it's help.
Another workaround would be to wrap up your web request in a service that gets injected into the PCL.
Not ideal but thats what Im doing for now.
Before getting into major complications with platform specific "simple" handlers and IoC magic, I suggest you validate a couple of things. After all the whole point of Xamarin and Mono are to avoid all these black santeria hacks to begin with.
If this doesn't work, I would then science the shit of it, and go ballistic... but start here first:
Make sure your platform specific project (MyProject.iOS, or MyProject.Android) HAVE the System.Net.Http referenced under references
Make sure your PCL is targeting the a Profile that is supported by your platform specific project targets (as of the time of this writing, I use "PCL 4.5 - Profile78" with iOS and Android projects)
Good luck!
I create a c# console project to read the excel document on the sharepoint server, everything works fine. The problem is when I try to read the excel file data in a silverlight application, a exception popped up as below:
{System.ServiceModel.CommunicationException: An error occurred while trying to make a request to URI 'http://phc/_vti_bin/excelservice.asmx'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details. ---> System.Security.SecurityException ---> System.Security.SecurityException: Security error.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
--- End of inner exception stack trace ---
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
at CERViewer.ESW.ExcelServiceSoapClient.ExcelServiceSoapClientChannel.EndOpenWorkbook(IAsyncResult result)
at CERViewer.ESW.ExcelServiceSoapClient.CERViewer.ESW.ExcelServiceSoap.EndOpenWorkbook(IAsyncResult result)
at CERViewer.ESW.ExcelServiceSoapClient.EndOpenWorkbook(IAsyncResult result, ObservableCollection`1& status)
at CERViewer.ESW.ExcelServiceSoapClient.OnEndOpenWorkbook(IAsyncResult result)
at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)}
The source code:
private void GetFeatures()
{
ExcelServiceSoapClient = new ExcelServiceSoapClient();
string targetWorkbookPath = "http://phc/Shared%20Documents/sample.xlsx";
xlservice.OpenWorkbookCompleted += new EventHandler<OpenWorkbookCompletedEventArgs>(xlservice_OpenWorkbookCompleted);
xlservice.OpenWorkbookAsync(targetWorkbookPath, "en-US", "en-US");
}
void xlservice_OpenWorkbookCompleted(object sender, OpenWorkbookCompletedEventArgs e)
{
sessionId = (string)e.Result; //exception here!!!
}
I tried the ways below, but they all failed.
1: create the file and put it on the "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi\", but it failed again.
2: open the cross-domain workbook and data connection access in the sharepoint server, here
I am totally new to sharepoint and silverlight development, I search around on the net but can't find the answer. anyone could help me???
I fixed the problem by putting the clientaccesspolicy.xml file in the server root.
We have some solution that we built against a MOSS farm one of which includes a timer job. This job has been working just fine for months. Recently the administrator enlisted another server into the farm, and our timer job automatically started running on this new machine. As soon as this switch happened our timer job started yielding the error below (found this in the SP logs).
At first I thought it was a rights issue, but the timer service on the machine where it worked before and the new one are running under the same domain account. It seems to be failing while looping the site list in a site collection, on just one of the sites/webs (code snippet below). I know that this domain account has access to this because it works on the other box under same account. Does anyone have any ideas on why this cryptic error is occurring? Or if any special procedure needs to be done on this new machine to ensure it has proper ACL's for all databases in the MOSS farm?
Code:
public static void Main(string[] args)
{
SPSecurity.RunWithElevatedPrivileges(delegate() { setInputParameters(); });
}
private static void setInputParameters()
{
SPFarm farm = SPFarm.Local;
SPWebService service = farm.Services.GetValue<SPWebService>("");
foreach (SPWebApplication webApp in service.WebApplications)
{
foreach (SPSite siteCollection in webApp.Sites)
{
using(siteCollection)
{
siteCollection.CatchAccessDeniedException = false;
try
{
/* Here is the line that it fails on */
foreach (SPWeb web in siteCollection.AllWebs)
Exception:
The Execute method of job definition LMSDataImport (ID 4b37b285-ef8a-407c-8652-391639449790) threw an exception.
More information is included below.
The type initializer for 'Microsoft.SharePoint.Administration.SPPersistedObjectCollection`1' threw an exception.
Exception stack trace:
at Microsoft.SharePoint.Administration.SPPersistedObjectCollection`1.get_BackingList()
at Microsoft.SharePoint.Administration.SPPersistedObjectCollection`1.GetEnumerator()
at Microsoft.SharePoint.Administration.SPAlternateUrlCollectionManager.LookupAlternateUrl(Uri canonicalRequestUri)
at Microsoft.SharePoint.Administration.SPAlternateUrl.LookupCore(Uri uri, SPFarm farm)
at Microsoft.SharePoint.Administration.SPWebApplication.Lookup(SPFarm farm, Uri requestUri, Boolean fallbackToHttpContext, SPAlternateUrl& alternateUrl, SiteMapInfo& hostHeaderSiteInfo, Boolean& lookupRequiredContext)
at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)
at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite)
at Microsoft.SharePoint.Administration.SPSiteCollection.get_Item(String strSiteName)
at Microsoft.SharePoint.Administration.SPSiteCollection.get_Item(Int32 index)
at Microsoft.SharePoint.Administration.SPSiteCollection.ItemAtIndex(Int32 iIndex)
at Microsoft.SharePoint.SPBaseCollection.SPEnumerator.System.Collections.IEnumerator.get_Current()
at LMSDataImporter.setInputParameters()
at Microsoft.SharePoint.SPSecurity.CodeToRunElevatedWrapper(Object state)
at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2()
at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
at Axian.AxianCalendar.LMSDataImporter.Main(String[] args)
at Microsoft.SharePoint.Administration.SPTimerJobInvoke.Invoke(TimerJobExecuteData& data, Int32& result)
Check the DLLs for SharePoint, do all exists and all are the same version? Try putting a catch for the TypeInitializationException, and see what is wrong inside that exception.
It's not a solution, but as a workaround in the interim, I think my suggestion to one of your other questions here:
How do you instruct a SharePoint Farm to run a Timer Job on a specific server?
will keep you running while you investigate further.
Check the NLB (Network Load Balancing) configuration. Most of the time SharePoint and applications integrated to it fails when NLB changes its state. There is a patch available to solve this problem. Just a suggestion. Not sure if this is the reason. But I have faced a similar issue and the root cause was an NLB bug
A Type init exception just means an exception occurred in the .ctor of the class (as you probably know). The real exception should be in the InnerException property - can you get your hands on this? Likely it's stemming from the database alright, from Microsoft.SharePoint.Administration.SPPersistedChildCollection InitializeFromDatabse method.
Can you look into the sharepoint logs (on that errant server) for information about the database error, it will be there. Reading logs are a pain, but not if you install the ULS Log Viewer feature from http://www.codeplex.com/features
Since the stacktrace has SPAlternateUrl tinkering furhter up the stack, perhaps your zones are misconfigured (and do not include a mapping for this new server's machine name) - granted, it shouldn't fail this bad, but what can you do.
You can filter the ULS logs by source.
-Oisin