Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How do I correctly save a record as a child of another record with LINQ?

Posted on 2009-04-13
17
Medium Priority
?
265 Views
Last Modified: 2013-11-12
I have a WCF service for a Silverlight app that saves a record with a child record. When I was initially testing the form I didn't create a child record and it worked. Now that I have added the creation of a child record on the save, it crashes when I try to retrieve the record and gives the following response:

System.ServiceModel.CommunicationException was unhandled by user code
  Message="The remote server returned an error: NotFound"
  StackTrace:
       at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult 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 Cognition_Pool.CognitionPool.Cognition_Pool_ServiceClient.Cognition_Pool_ServiceClientChannel.EndRetrieveUserByName(IAsyncResult result)
       at Cognition_Pool.CognitionPool.Cognition_Pool_ServiceClient.Cognition_Pool.CognitionPool.Cognition_Pool_Service.EndRetrieveUserByName(IAsyncResult result)
       at Cognition_Pool.CognitionPool.Cognition_Pool_ServiceClient.OnEndRetrieveUserByName(IAsyncResult result)
       at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)
  InnerException: System.Net.WebException
       Message="The remote server returned an error: NotFound"
       StackTrace:
            at System.Net.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
            at System.Net.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
            at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
       InnerException: System.Net.WebException
            Message="The remote server returned an error: NotFound"
            StackTrace:
                 at System.Net.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
                 at System.Net.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
                 at System.Net.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)
            InnerException:

I tried the solutions given at http://silverlight.net/forums/t/53458.aspx as suggested under another question.
[OperationContract]
        public void CreateUser(User user)
        {
            CognitionPoolDatabaseDataContext db = new CognitionPoolDatabaseDataContext();
 
            // Add an Event to the User to represent the creation
            Event createEvent = new Event();
            createEvent.EventId = Guid.NewGuid();
            createEvent.EventDate = DateTime.Now;
            createEvent.EventCodeId = GetEventCodeByName(EVENT_CODE_TYPE_CREATE).EventCodeId;
            createEvent.CausingUserId = user.UserId;
 
            user.Events.Add(createEvent);
 
            db.Users.InsertOnSubmit(user);
            db.SubmitChanges();
        }
 
[OperationContract]
        public User RetrieveUserByName(string UserName)
        {
            CognitionPoolDatabaseDataContext db = new CognitionPoolDatabaseDataContext();
            var query = from u in db.Users
                        where u.Username == UserName
                        select u;
 
            User result = null;
 
            if (query.Count() == 1)
            {
                result = query.Single();
            }
 
            return result;
        }

Open in new window

0
Comment
Question by:zainta
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 8
17 Comments
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 24136071
modify code as shown below so u will know what is the error whjile debugging ..
OperationContract]
        public User RetrieveUserByName(string UserName)
        {
try
{
            CognitionPoolDatabaseDataContext db = new CognitionPoolDatabaseDataContext();
            var query = from u in db.Users
                        where u.Username == UserName
                        select u;
 
            User result = null;
 
            if (query.Count() == 1)
            {
                result = query.Single();
            }
 
            return result;
}
catch(Exception ex)
{
 
return null;
}
        }

Open in new window

0
 

Author Comment

by:zainta
ID: 24136470
I modified the method to be as you suggested. The exception occurs after it exists the method. The following is where the debugged shows the exception occurring. This is from the Reference.cs file.
public System.IAsyncResult BeginRetrieveUserById(System.Guid userId, System.AsyncCallback callback, object asyncState) {
                object[] _args = new object[1];
                _args[0] = userId;
                System.IAsyncResult _result = base.BeginInvoke("RetrieveUserById", _args, callback, asyncState);
                return _result;
            }

Open in new window

0
 

Author Comment

by:zainta
ID: 24136506
I'm sorry, I can't figure out how to edit the comment I made but I posted the wrong code from the Reference.cs file. It looks the same but I am going to post the correct code anyway. The exception does occur in the reference file after the method with the try catch has completed and ended.
public Cognition_Pool.CognitionPool.User EndRetrieveUserByName(System.IAsyncResult result) {
                object[] _args = new object[0];
                Cognition_Pool.CognitionPool.User _result = ((Cognition_Pool.CognitionPool.User)(base.EndInvoke("RetrieveUserByName", _args, result)));
                return _result;
            }

Open in new window

0
Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 24136522
this is at the client side rt ?.. u have to debug on the server side to get the exception
0
 

Author Comment

by:zainta
ID: 24136994
I put a break point in the service method. When the server reaches it it drops into the debugger. I can step all the way through the entire service method and out of it. As soon as I leave the service method, it crashes in the Referece.cs file.
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 24137383
can u post ur config file ? change this line
<binding name="BasicHttpBinding_urServiceName" maxBufferSize="2147483647"
                    maxReceivedMessageSize="2147483647">  
both at the server side and the client side. change the value of maxBufferSize and maxReceivedMessageSize to 2147483647 (int.Max)
0
 

Author Comment

by:zainta
ID: 24143234
Sorry for the long time between responses.

Below is the system.servicemodel part of the web.config:
<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="myServicesBinding" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
          <readerQuotas maxDepth="50" maxArrayLength="2147483647" maxStringContentLength="2147483647"/>
        </binding>
      </basicHttpBinding>
    </bindings>
		<behaviors>
			<serviceBehaviors>
				<behavior name="Cognition_Pool_Web.Cognition_Pool_ServiceBehavior">
					<serviceMetadata httpGetEnabled="true"/>
					<serviceDebug includeExceptionDetailInFaults="true"/>
				</behavior>
			</serviceBehaviors>
		</behaviors>
		<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
		<services>
			<service behaviorConfiguration="Cognition_Pool_Web.Cognition_Pool_ServiceBehavior" name="Cognition_Pool_Web.Cognition_Pool_Service">
				<endpoint address="" binding="basicHttpBinding" contract="Cognition_Pool_Web.Cognition_Pool_Service"/>
				<endpoint address="mex" binding="basicHttpBinding" contract="IMetadataExchange"/>
			</service>
		</services>
	</system.serviceModel>
 
Below is the entire webservice config file:
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_Cognition_Pool_Service" maxBufferSize="2147483647"
                    maxReceivedMessageSize="2147483647">
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:49426/Cognition%20Pool%20Service.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Cognition_Pool_Service"
                contract="CognitionPool.Cognition_Pool_Service" name="BasicHttpBinding_Cognition_Pool_Service" />
        </client>
    </system.serviceModel>
</configuration>

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 24144898
set maxDepth also to int.MaxValue and try..
0
 

Author Comment

by:zainta
ID: 24145012
Still got the same error message after making that modification.
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 24145129
i think this shud work add this section tour behaviour area
<behaviors>
<serviceBehaviors>
<behavior name="Cognition_Pool_Web.Cognition_Pool_ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<!--add this-->
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<!--till here-->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>

Open in new window

0
 
LVL 29

Accepted Solution

by:
Gautham Janardhan earned 1000 total points
ID: 24145246
0
 

Author Comment

by:zainta
ID: 24146974
I added the line to my behaviors section and it looks like this now (code snippet). When I ran it, it crashed during the loading sequence where it has to retrieve some data with the error I am getting now (but on a record that has no children).
<behaviors>
      <serviceBehaviors>
        <behavior name="CognitionPoolBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 24148413
can u post ur config file once again after all the modifications put in ..
0
 

Author Comment

by:zainta
ID: 24153867
It's still crashing, same exception:

System.ServiceModel.CommunicationException was unhandled by user code
  Message="The remote server returned an error: NotFound"
  StackTrace:
       at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult 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 Cognition_Pool.CognitionPool.Cognition_Pool_ServiceClient.Cognition_Pool_ServiceClientChannel.EndRetrieveUserByName(IAsyncResult result)
       at Cognition_Pool.CognitionPool.Cognition_Pool_ServiceClient.Cognition_Pool.CognitionPool.Cognition_Pool_Service.EndRetrieveUserByName(IAsyncResult result)
       at Cognition_Pool.CognitionPool.Cognition_Pool_ServiceClient.OnEndRetrieveUserByName(IAsyncResult result)
       at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)
  InnerException: System.Net.WebException
       Message="The remote server returned an error: NotFound"
       StackTrace:
            at System.Net.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
            at System.Net.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
            at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
       InnerException: System.Net.WebException
            Message="The remote server returned an error: NotFound"
            StackTrace:
                 at System.Net.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
                 at System.Net.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
                 at System.Net.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)
            InnerException:


Web.Config service section:
<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="myServicesBinding" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
          <readerQuotas maxDepth="2147483647" maxArrayLength="2147483647" maxStringContentLength="2147483647"/>
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Cognition_Pool_Web.Cognition_Pool_ServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
		<services>
			<service behaviorConfiguration="Cognition_Pool_Web.Cognition_Pool_ServiceBehavior" name="Cognition_Pool_Web.Cognition_Pool_Service">
				<endpoint bindingConfiguration="myServicesBinding" address="" binding="basicHttpBinding" contract="Cognition_Pool_Web.Cognition_Pool_Service"/>
				<endpoint address="mex" binding="basicHttpBinding" contract="IMetadataExchange"/>
			</service>
		</services>
	</system.serviceModel>
 
Webservice Config file:
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_Cognition_Pool_Service" maxBufferSize="2147483647"
                    maxReceivedMessageSize="2147483647">
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:49426/Cognition%20Pool%20Service.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Cognition_Pool_Service"
                contract="CognitionPool.Cognition_Pool_Service" name="BasicHttpBinding_Cognition_Pool_Service" />
        </client>
    </system.serviceModel>
</configuration>

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 24154815
this particular method does it takes time to complete ? and when do u get the error ? immediately or after a while ?
0
 

Author Comment

by:zainta
ID: 24155994
The error occurs immediately. It just tries to retrieve a single record and return it. As stated earlier, it works perfectly if the record has no foreign key values but if it does then I get this error.
0
 

Author Comment

by:zainta
ID: 24174153
It turned out that my problem had the same solution as this:
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_23823298.html
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question