Solved

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

Posted on 2009-04-13
17
255 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
  • 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
 
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

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 250 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

What my article will show is if you ever had to do processing to a listbox without being able to just select all the items in it. My software Visual Studio 2008 crystal report v11 My issue was I wanted to add crystal report to a form and show…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
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…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

757 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now