A journey towards the formation of the WCF development framework -- troubleshooting of common issues in the WCF Application

Source: Internet
Author: User

 

This article continues with the previous articles about the WCF development framework, and introduces some experience and knowledge about WCF. It mainly introduces the problems encountered during the use of WCF development and the solutions, mark yourself and provide solutions for later users, including dynamically modifying the content of the WCF configuration and standardizing the calling and processing of the WCF client.

 

1. dynamically modify the content of the WCF Configuration

 

In the software logon interface, users need to switch between the Intranet and the Internet. The intranet and Internet addresses in the configuration file are different. Therefore, you need to modify the application configuration file dynamically, then, update the node content, as shown in the following figure.

 

 

 

Modify the C # code of a WCF node as follows: www.2cto.com

 

Private void ChangeConfig ()

{

Bool isIntranet = radNetType. EditValue. ToString () = "intranet ";

If (isIntranet)

{

UpdateConfig ("192.168.1.2", "8002 ");

}

Else

{

UpdateConfig ("219.136.1.2", "8002 ");

}

}

 

Private void UpdateConfig (string serverIPAddress, string serverPort)

{

// Configuration config = ConfigurationManager. OpenExeConfiguration (Assembly. GetEntryAssembly (). Location );

Configuration config = ConfigurationManager. OpenExeConfiguration (ConfigurationUserLevel. None );

ConfigurationSectionGroup sct = config. SectionGroups ["system. serviceModel"];

ServiceModelSectionGroup serviceModelSectionGroup = sct as ServiceModelSectionGroup;

ClientSection clientSection = serviceModelSectionGroup. Client;

 

Foreach (ChannelEndpointElement item in clientSection. Endpoints)

{

String pattern = "://.*/";

String address = item. Address. ToString ();

If (address. ToLower (). Contains ("localhost "))

Return;

 

String replacement = string. Format (": // {0 }:{ 1}/", serverIPAddress, serverPort );

Address = Regex. Replace (address, pattern, replacement );

Item. Address = new Uri (address );

}

 

Config. Save (ConfigurationSaveMode. Modified );

ConfigurationManager. RefreshSection ("system. serviceModel ");

}

 

 

For convenience of debugging, in the Code of the configuration file, if the address is determined to be localhost, the switch is not modified.

 

 

 

2. Standardize the call handling of the WCF client.

 

When creating a WCF Service client instance, we may create and call a client together, that is, create a global WCF Service client instance in the form at the top of the form.

 

Public partial class FrmParkUser: BaseDock

{

Private DeviceUserServiceClient client = new DeviceUserServiceClient ();

Public string ID = string. Empty;

 

Public FrmParkUser ()

{

InitializeComponent ();

}

.................

 

 

In actual use of the wcf client, we may call this method.

 

This. winGridViewPager1.PagerInfo. RecordCount = client. GetRecordCount2 (where );

This. winGridViewPager1.DataSource = client. SearchParkUser (where, this. winGridViewPager1.PagerInfo );

 

 

OK. In fact, this operation seems to be okay and can be used smoothly. However, since the wcf client has a timeout time, it may be static for a while, when you refresh data on the interface, you will find the following error: "communication object System. serviceModel. channels. serviceChannel cannot be used for communication because it is in the "error" status. "

 

Or some strange error messages.

 

Since the above call is not good, how should we call the client? Someone calls it like this.

 

Using (var client = new SomeWCFServiceClient ())

{

// Do something with the client

 

}

 

 

In fact, this operation is even worse, and there will be a red error above. The call method recommended by Microsoft should be like this.

 

Try

{

...

Client. Close ();

}

Catch (CommunicationException e)

{

...

Client. Abort ();

}

Catch (TimeoutException e)

{

...

Client. Abort ();

}

Catch (Exception e)

{

...

Client. Abort ();

Throw;

}

 

 

However, if the call frequency is frequent, it is really indecent and the management is also very uncomfortable. Is there a better way to avoid errors and call the wcf client correctly? Of course, the following method is a better solution. After actual testing, the effect is good.

 

1. Create an extension helper class. The Code is as follows:

 

/// <Summary>

/// WCF Service packaging class to avoid service errors caused by Using or other methods

/// </Summary>

Public static class WcfExtensions

{

Public static void Using <T> (this T client, Action <T> work)

Where T: ICommunicationObject

{

Try

{

Work (client );

Client. Close ();

}

Catch (CommunicationException e)

{

Client. Abort ();

}

Catch (TimeoutException e)

{

Client. Abort ();

}

Catch (Exception e)

{

Client. Abort ();

Throw;

}

}

}

 

 

Then, the actual call is as follows, which looks very simple. This is the proxy client that needs to be created. Even if the operation is not performed for a long time, no timeout or other error messages will occur.

 

Private void GetTable ()

{

New EnterpriseServiceClient (). Using (enterpriseClient =>

{

DataTable dt = enterpriseClient. GetAllForLookUp ();

This. searchPark. Properties. DisplayMember = "PARK_NAME ";

This. searchPark. Properties. ValueMember = "ID ";

This. searchPark. Properties. DataSource = dt;

});

 

New ManufacturerServiceClient (). Using (manufacturerClient =>

{

ManufacturerInfo [] manuList = manufacturerClient. GetAll ();

This. searchCompany. Properties. DisplayMember = "CompanyName ";

This. searchCompany. Properties. ValueMember = "ID ";

This. searchCompany. Properties. DataSource = manuList;

});

}

 

 

Or the following example.

 

ManufacturerInfo info = null;

New ManufacturerServiceClient (). Using (manufacturerClient =>

{

Info = manufacturerClient. FindByID (searchCompany. EditValue. ToString ());

});

If (info! = Null)

{

This.txt CompanyAddr. Text = info. CompanyAddr;

}

 

 

 

 

Main research technologies: code generation tools, secondary development of Visio, water delivery management software, and other shared software development

Reprinted please indicate the source:

Written by: Wu huacong http://www.iqidi.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.