Silverlight 4 and WCF Data Service

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

Silverlight 4 and WCF Data Service

smlyttle
I am new to NLog and I have been reviewing the Silverlight and WCF Data Service examples, but I cannot get logging working on my Silverlight application using a WCF Data Service.  Can someone look at my code below and let me know what I am doing wrong?  My goal is to log to a text file first (and then log to MS SQL server after getting the text logging working), but logging to a text file is currently not working.

I am running Visual Studio 2010 SP1 in Adminstrator mode when performing my tests (on a Windows 7 Pro SP1 machine).

Silverlight.Web project

Begin Webservice.cs code

namespace EndOfTheRope.Web.Services {

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class NLogReceiver : ILogReceiverServer {

        public void ProcessLogMessages(NLogEvents events) {
            DateTime baseTimeUtc = new DateTime(events.BaseTimeUtc, DateTimeKind.Utc);

            foreach(var ev in events.Events) {
                LogLevel level = LogLevel.FromOrdinal(ev.LevelOrdinal);
                //string loggerName = events.LoggerNames[ev.LoggerOrdinal];
                string loggerName = events.Strings[ev.LoggerOrdinal];

                Logger logger = LogManager.GetLogger(loggerName);
                var logEventInfo = new LogEventInfo();
                logEventInfo.Level = level;
                logEventInfo.LoggerName = loggerName;
                logEventInfo.TimeStamp = baseTimeUtc.AddTicks(ev.TimeDelta);
                logEventInfo.Properties.Add("ClientName", events.ClientName);
                for(int i = 0; i < events.LayoutNames.Count; ++i) {
                    logEventInfo.Properties.Add(events.LayoutNames[i], ev.Values[i]);
                }
                logger.Log(logEventInfo);
            }
        }

    }
}
End Webservice.cs code

Begin Server's NLog.config file

<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <target name="file" xsi:type="File"
        layout="${longdate} ${logger} ${event-context:ClientName} ${event-context:message}"
        fileName="c:/nlog/nlog2.txt"
        keepFileOpen="false"
        encoding="iso-8859-2" />
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="file" />
  </rules>
</nlog>
End Server's NLog.config file

Begin Server's Web.config file
<?xml version="1.0" encoding="utf-8"?>

<configuration>

  <configSections>
    <sectionGroup name="system.serviceModel">
      <section name="domainServices" type="System.ServiceModel.DomainServices.Hosting.DomainServicesSection, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" allowDefinition="MachineToApplication" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="DomainServiceModule" preCondition="managedHandler" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <system.web>
    <httpModules>
      <add name="DomainServiceModule" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </httpModules>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
  </system.web>
  <connectionStrings>
    <add name="GreenEntities" connectionString="metadata=res://*/Models.ProjectGreen.csdl|res://*/Models.ProjectGreen.ssdl|res://*/Models.ProjectGreen.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=TestServer01;Initial Catalog=Green;Persist Security Info=True;User ID=********;Password=*********;MultipleActiveResultSets=True;Application Name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
          <behavior name="EndOfTheRope.Web.NLogReceiverBehavior">
            <serviceMetadata httpGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="false"/>
          </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <pollingDuplex>
        <binding name="myPollingDuplex" duplexMode="MultipleMessagesPerPoll" closeTimeout="00:00:30" inactivityTimeout="00:00:30" receiveTimeout="00:01:00" openTimeout="00:01:00" sendTimeout="00:01:00" />
      </pollingDuplex>
    </bindings>
    <domainServices>
      <endpoints>
        <add name="OData" type="System.ServiceModel.DomainServices.Hosting.ODataEndpointFactory, System.ServiceModel.DomainServices.Hosting.OData, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </endpoints>
    </domainServices>
    <extensions>
      <bindingExtensions>
        <add name="pollingDuplex" type="System.ServiceModel.Configuration.PollingDuplexHttpBindingCollectionElement,System.ServiceModel.PollingDuplex, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </bindingExtensions>
    </extensions>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <services>
      <service behaviorConfiguration="EndOfTheRope.Web.NLogReceiverBehavior" name="EndOfTheRope.Web.Service.NLogReceiver">
        <endpoint address="" binding="basicHttpBinding" contract="NLog.LogReceiverService.ILogReceiverServer">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
      <service name="EndOfTheRope.Web.Services.ChatService">
        <endpoint address ="" binding="pollingDuplex" bindingConfiguration="myPollingDuplex"
                  contract="EndOfTheRope.Web.Services.ChatService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
  </system.serviceModel>
</configuration>
End Server's Web.config file

Begin WSDL file
  <?xml version="1.0" encoding="utf-8" ?>
- <wsdl:definitions name="NLogReceiver" targetNamespace="http://tempuri.org/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:tns="http://tempuri.org/" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:i0="http://nlog-project.org/ws/" xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract" xmlns:wsa10="http://www.w3.org/2005/08/addressing" xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata">
  <wsdl:import namespace="http://nlog-project.org/ws/" location="http://localhost:60219/Services/NLogReceiver.svc?wsdl=wsdl0" /> 
  <wsdl:types /> 
- <wsdl:binding name="BasicHttpBinding_ILogReceiverServer" type="i0:ILogReceiverServer">
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http" /> 
- <wsdl:operation name="ProcessLogMessages">
  <soap:operation soapAction="http://nlog-project.org/ws/ILogReceiverServer/ProcessLogMessages" style="document" /> 
- <wsdl:input>
  <soap:body use="literal" /> 
  </wsdl:input>
- <wsdl:output>
  <soap:body use="literal" /> 
  </wsdl:output>
  </wsdl:operation>
  </wsdl:binding>
- <wsdl:service name="NLogReceiver">
- <wsdl:port name="BasicHttpBinding_ILogReceiverServer" binding="tns:BasicHttpBinding_ILogReceiverServer">
  <soap:address location="http://localhost:60219/Services/NLogReceiver.svc" /> 
  </wsdl:port>
  </wsdl:service>
  </wsdl:definitions>
End WSDL file

Silverlight Client project

Begin App.xaml.cs file
namespace EndOfTheRope {
    public partial class App : Application {
        public App() {
            this.Startup += this.Application_Startup;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();

            LogManager.ThrowExceptions = true;

            var target = new LogReceiverWebServiceTarget();
            target.EndpointAddress = new Uri(HtmlPage.Document.DocumentUri, "NLogReceiver.svc").ToString();
            target.Parameters.Add(new MethodCallParameter("message", "${message}"));
            target.Parameters.Add(new MethodCallParameter("date", "${longdate}"));

            var buffer = new BufferingTargetWrapper(target) { BufferSize = 10, FlushTimeout = 20 };

            SimpleConfigurator.ConfigureForTargetLogging(buffer);
        }

        private void Application_Startup(object sender, StartupEventArgs e) {
            this.RootVisual = new MainPage();
        }


        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) {
            // If the app is running outside of the debugger then report the exception using
            // a ChildWindow control.
            if(!System.Diagnostics.Debugger.IsAttached) {
                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled.
                // For production applications this error handling should be replaced with something that will
                // report the error to the website and stop the application.
                e.Handled = true;
                ChildWindow errorWin = new ErrorWindow(e.ExceptionObject);
                errorWin.Show();
            }
        }
    }
}
End App.xaml.cs file

Begin ServiceReferences.ClientConfig file
<configuration>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_ILogReceiverServer" maxBufferSize="2147483647"
            maxReceivedMessageSize="2147483647">
          <security mode="None">
            <transport>
              <extendedProtectionPolicy policyEnforcement="Never" />
            </transport>
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:60219/NLogReceiver.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_ILogReceiverServer"
                contract="NLog.LogReceiverService.ILogReceiverClient" name="NLogReceiver" />
    </client>
  </system.serviceModel>
</configuration>
End ServiceReferences.ClientConfig file

Begin Client's NLog.config file
<nlog>
</nlog>
End Client's NLog.config file

Begin Silverlight UserControl for logging test
namespace EndOfTheRope.Views {
    public partial class ResourceView : UserControl {

        private static Logger logger = LogManager.GetCurrentClassLogger();

        public ResourceView() {
            InitializeComponent();

            // log some events
            this.Loaded += (sender, e) => logger.Info("Page loaded");
            this.LayoutUpdated += (sender, e) => logger.Debug("Layout updated");
            this.SizeChanged += (sender, e) => logger.Debug("Size changed to {0}x{1}", e.NewSize.Width, e.NewSize.Height);
            this.KeyDown += (sender, e) => logger.Debug("Key down '{0}'", e.Key);
            this.Unloaded += (sender, e) => logger.Info("Unloaded");
        }

        private void btnTest_Click(object sender, RoutedEventArgs e) {
            logger.Info("Info");
            logger.Debug("Debug");
            logger.Fatal("Fatal");
        }


    }
}
End Silverlight UserControl for logging test


Reply | Threaded
Open this post in threaded view
|

Re: Silverlight 4 and WCF Data Service

smlyttle
I think I just figured out my issue.  My NLogReceiver.svc was in a folder named "Services" in my Project and NLog.config was in the Project's root folder; once I moved NLogReceiver.svc to the Project's root folder I started getting the logging alerts in my text file.
Reply | Threaded
Open this post in threaded view
|

Re: Silverlight 4 and WCF Data Service

Baard
Just a thought; This problem might not have occurred if the <nlog> configuration was placed in the web.config file (instead of in a standalone nlog.config file)?

Like in this example:

<configuration>

  <configSections>
      <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
        <target name="file" xsi:type="File" fileName="${basedir}/logs/NLog.log" keepFileOpen="false" encoding="iso-8859-2" />
        <target name="trace" xsi:type="Trace" />
    </targets>
    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
        <logger name="*" minlevel="Debug" writeTo="trace" />
    </rules>
  </nlog> 

  . . . etc
 
Reply | Threaded
Open this post in threaded view
|

Re: Silverlight 4 and WCF Data Service

Globecoder
In reply to this post by smlyttle
I ran into the same issue as that smlyttle ran into with latest NLog 2.0. I figured out the issue was in the app.xaml.cs. I had to change this line:

target.EndpointAddress = new Uri(HtmlPage.Document.DocumentUri, "NLogReceiver.svc").ToString();

to

target.EndpointAddress = new Uri(HtmlPage.Document.DocumentUri, "Services/NLogReceiver.svc").ToString();

Everything worked fine afterwards.

HTH.
Reply | Threaded
Open this post in threaded view
|

Re: Silverlight 4 and WCF Data Service

jbritto25
I am also trying to do same thing ... Where you have to put the WSDL file ?