Daily Archives

Articles indexed Friday July 6 2012

Page 4/16 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How to access the java vaiables in the mule flows

    - by RohanRasane
    Scenario I have a variable in the Java file, which I want to access in the mule config xml. How do I do that. Example - There is a web service which passes params like this localhost/apiname?name="dynamic data" So while hitting the web service I want to pass param "name" as a dynamic data. How do I do that. I assume if I'm able to access the Java variable in the xml file then that will be possible.

    Read the article

  • parse complex xml using Sax xml parsing in android

    - by hardik joshi
    Hello i am new in android and i am currently using SAX parsing in android. Following is my xml file. <response> <peoples> <name>abc</name> <age> 20</age> <info> <address>USA</address> <family>parents</family> </info> </people> <people> <name>abc</name> <age> 20</age> <info> <address>USA</address> <family>parents</family> </info> </people> </response> How to parse this xml using SAX parser. Please help me to find this.Thank you in advance.

    Read the article

  • Spring MVC 3.1 How to access HttpSession in Custom Authentication Provider (which implements AuthenticationProvider)

    - by user1506231
    My application calls a web service during the Authentication process (as shown in code below). How can I save some information in HttpSession during this process? This information like customer-account-number will be used in various other places in the application after the user is logged in. Is it possible to pass HttpSession parameter to the MyServiceManager's static login method? public class MyAuthenticationManager implements AuthenticationProvider { @Override public boolean supports(Class<? extends Object> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } @Override public Authentication authenticate(Authentication authentication) { //MyServiceManager.login - makes a call to web service if(MyServiceManager.login(authentication.getName(), authentication.getCredentials().toString(), XXX_HTTP_SESSION_XXX)) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority> (); authorities.add(new GrantedAuthorityImpl("ROLE_USER")); authorities.add(new GrantedAuthorityImpl("ROLE_SUPERVISOR")); return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials(),authorities); } else { return null; } } }

    Read the article

  • logic for a php function

    - by danish hashmi
    i need to make a php code for checking hotel room avaibility where user from the present day can book rooms upto 90 days or less and there are total 30 rooms available in the hotel,so if once i store the data for a user like his booking from one date till another next time if i want to check the avaibility how should i do it in php,what would be the logic. obviously i simple query like this isn't correct for eg $this->db->select('*') ->from('default_bookings') ->where('booking_from <',$input['fromdate']) ->where('booking_till >',$input['tilldate']);

    Read the article

  • wordpress: cant get category id when SEO URL is turned on

    - by John K
    <?php /* Plugin Name: Members */ function myFilter2($query) { if ($query->is_category) { $currently_listing_categories = $query->query_vars['category__in']; print_r($currently_listing_categories); } } add_filter('pre_get_posts','myFilter2'); ?> This plugin display the category ids when the url is not SEO friendly http://domain.com/wplab/wpla4/?cat=4 . but when I turn on SEO http://domain.com/wplab/wpla4/category/members/ the array is empty how can I get the category id with SEO friendly urls

    Read the article

  • iOS - when to remove subviews from UITableViewCell

    - by Milad Ghattavi
    I have a UITableView which a UIImage is added as a subview to each cell of it. The images are PNG transparent. The problem is when I scroll through the UITableView, the images get overlapped and then I receive the memory warning and stuff. here's the current code for configuring a cell: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } int cellNumber = indexPath.row + 1; NSString *cellImage1 = [NSString stringWithFormat:@"c%i.png", cellNumber]; UIImage *theImage = [UIImage imageNamed:cellImage1]; UIImageView *cellImage = [[UIImageView alloc] initWithImage:theImage]; [cell.contentView addSubview:cellImage]; return cell; } I know the code for removing the UIImage subview would be like: [cell.imageView removeFromSuperview]; But I don't know where to put it. I've placed it between all the lines; even added an else, in the if statement. didn't seem to work!

    Read the article

  • Local variable and Try/Catch

    - by 3D-kreativ
    I get an error, a red line below the variable intAge in the if-statement in the code. It says the variable is local, but how could it be local when it is declared in the beginning of the code? Does it have to do with the Try/Catch part? The reason why my code looks like it does, is just beacuse I have to use a Try/Catch in the code for this task. Preciate some suggestions to solve this in a similiar and correct way? Thanks! int intAge; try { intAge = int.Parse(age); } catch (Exception) { MessageBox.Show("Enter an age in numbers!","Error!"); } finally { } // Check input if (intAge < 1) { inputOk = false; errorMessage = "Please enter 1 or higher!"; }

    Read the article

  • list permutations in haskell

    - by turingcomplete
    So I'm new to haskell and I've been playing with it for a while now. I want to get my function that outputs all list permutations to work. I have written 2 implementations, one works well, the other is giving me an error. Any help would be awesome. This is the first (working) implementation: permute [] = [[]] permute xs = [y| x <- xs, y <- map (x:) $ permute $ delete x xs] This one is giving me an error: permute [] = [[]] permute xs = map (\x -> map (x:) $ permute $ delete x xs) xs and here's the error message: Occurs check: cannot construct the infinite type: t0 = [t0] Expected type: [t0] Actual type: [[t0]] In the expression: map (x :) $ permute $ delete x xs In the first argument of `map', namely `(\ x -> map (x :) $ permute $ delete x xs)' I'd appreciate if someone could explain why I'm getting this error. Thanks

    Read the article

  • Create subdomain and set home and stats value for plesk 10.4.4 using API

    - by ilSavo
    I was able to create a subdomain in my plesk panel (linux serverm and plesk 10.4.4 ) using API (with a PHP script). But I'm not able to find a documentation online for just two things: How can I set the stats property to be "awstats" instead of "Nothing"? How can I set (if is it possible) the home directory for the created subdomain to be, for example /subdomains/my-subdomain? Thank you very much...

    Read the article

  • Backbone: rendering syntax

    - by ksol
    We're using Backbone.js in one of my team's projects, and this is the first time I use it. I've seen many times this kind of code (it's coffeescript, but clear enough I think. @ means this.) clients_view = new Homespa.Views.Orders.Clients.SectionView(collection: @options.clients) @$("#clients-section").html(clients_view.render().el) clients_search_view = new Homespa.Views.Orders.Clients.SearchView @$("#clients_search_modal").html(clients_search_view.render().el) Isn't there a better way to do this? I would expect to just call render on my view, and then everything's good, I shouldn't have to get the html and append/replace it by hand. Thanks for you time !

    Read the article

  • SOLR phrase query

    - by Alex
    I have a slight problem when searching with SOLR 4.0 and attempting a phrase query. I have a field called "idx_text_general_ci" which is a case insensitive (all lowercased) field made up of all fields. When I try and search for a phrase (marine fitter) my SOLR refuses to search for the phrase instead splitting the phrase into 2 words - /select?defType=edismax&q=idx_text_general_ci:marine%20fitter&debugQuery=true debugQuery=true output below: <lst name="debug"> <str name="rawquerystring">idx_text_general_ci:marine fitter</str> <str name="querystring">idx_text_general_ci:marine fitter</str> <str name="parsedquery"> (+(idx_text_general_ci:marine DisjunctionMaxQuery((id:fitter))))/no_coord </str> <str name="parsedquery_toString">+(idx_text_general_ci:marine (id:fitter))</str> As you can see above it splits the query into 2 parts (idx_text_general_ci:marine then id:fitter). THe problem I have is that I have an exact match for "marine fitter" that appears twice in the idx_text_general_ci field yet it's ranked with a lesser score than a document with the word "marine" appearing 3 times. I know this will not be the case if my SOLR was to search the field with the phrase as expected. If I wrap the phrase in quotes I get zero results. Any help or a nudge in the right direction would be much appreciated. Thanks in advance Alex

    Read the article

  • Using Jquery to add items in Listbox from Textbox

    - by Pratik Gupta
    I am stuck somewhere using jquery to append the list box from a text box. here is my jquery $("#btnAddSvc").click(function () { var svc = $("#<%= txtServiceName.ClientID %>").val(); //Its Let you know the textbox's value svc.appendTo("#<%=lstSvcName.ClientID %>"); }); I am using asp.net (c#) to develop my code <asp:Button ID="btnAddSvc" runat="server" Text=">>" Font-Size="Medium" /> <asp:ListBox ID="lstSvcName" runat="server" SelectionMode="Multiple" ToolTip="Selected Service Names" Width="169px"></asp:ListBox> can someone please help as i am not able to get the values in list box.

    Read the article

  • Check user language selection in NSIS MUI2

    - by wls
    I have multiple language packs in my NSIS installer, using the MUI2 interface. Now I try to select the language pack, which is installed by the "Typical" installation type according to the user's chosen setup language. My problem is, that I can't figure out, how to get the user's language selection. I already tried to access the variables $LANGUAGE and $mui.LangDLL.RegistryLanguage, as well as trying to compare a defined language string to a specific translation string, but without success.

    Read the article

  • Session in php are not enough clear to me

    - by Lulzim
    I find sessions in php kind of confusing, can anybody of you explain those to me. I have an example which is not working in my case: I register sessions this way, would you please tell me is this the right way of registering sessions //this is the page from where i register myusername in sessions if($count==1){ session_start(); $_SESSION['myusername'] = $_POST['myusername']; include("enterpincover.php"); } else { echo "Wrong Pin"; } here i check first whether the username is registered in sessions in oder to open his account , otherwise open again login. It works, if user is not loged in, it will show login page which is right, if user is loged it shows welcome message but not the Welcome the name of the user as I want. for ex: Welcome David <?php session_start(); if(isset($_SESSION['myusername'])) { echo 'Welcome '.$_SESSION['myusername']; } else { include("leftmodules.php"); include("rightmodules.php"); include("login.php"); } ?>

    Read the article

  • how to create a changing variable for fsolve

    - by Shun Miyamoto
    i want fsolve to calculate the output for different uc each time (increasing uc by 0.001 each time). each output from fsolve should be sent to a simulink model seperatly. so i set a loop to do so, but i believe that at the currenty constellation (if it will work)will just calculate 1000 different values? is there a way to send out the values seperately? if not, how can i create a parameter uc. that goes from 0 to say 1000? i tried uc=0:0.001:1000, but again, the demension doen't seem to fit. how do i create a function that takes the next element of a vector/matrix each time the function is called? uc=0; for i=0:1000 x0=[1,1,1]; y=x0(1); u=x0(2); yc=x0(3); options=optimset('Display','off'); x= fsolve(@myfun,x0,options,uc,d,spacing_amplitude,spacing_width); end best regards

    Read the article

  • libcurl - unable to download a file

    - by marmistrz
    I'm working on a program which will download lyrics from sites like AZLyrics. I'm using libcurl. It's my code lyricsDownloader.cpp #include "lyricsDownloader.h" #include <curl/curl.h> #include <cstring> #include <iostream> #define DEBUG 1 ///////////////////////////////////////////////////////////////////////////// size_t lyricsDownloader::write_data_to_var(char *ptr, size_t size, size_t nmemb, void *userdata) // this function is a static member function { ostringstream * stream = (ostringstream*) userdata; size_t count = size * nmemb; stream->write(ptr, count); return count; } string AZLyricsDownloader::toProviderCode() const { /*this creates an url*/ } CURLcode AZLyricsDownloader::download() { CURL * handle; CURLcode err; ostringstream buff; handle = curl_easy_init(); if (! handle) return static_cast<CURLcode>(-1); // set verbose if debug on curl_easy_setopt( handle, CURLOPT_VERBOSE, DEBUG ); curl_easy_setopt( handle, CURLOPT_URL, toProviderCode().c_str() ); // set the download url to the generated one curl_easy_setopt(handle, CURLOPT_WRITEDATA, &buff); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, &AZLyricsDownloader::write_data_to_var); err = curl_easy_perform(handle); // The segfault should be somewhere here - after calling the function but before it ends cerr << "cleanup\n"; curl_easy_cleanup(handle); // copy the contents to text variable lyrics = buff.str(); return err; } main.cpp #include <QString> #include <QTextEdit> #include <iostream> #include "lyricsDownloader.h" int main(int argc, char *argv[]) { AZLyricsDownloader dl(argv[1], argv[2]); dl.perform(); QTextEdit qtexted(QString::fromStdString(dl.lyrics)); cout << qPrintable(qtexted.toPlainText()); return 0; } When running ./maelyrica Anthrax Madhouse I'm getting this logged from curl * About to connect() to azlyrics.com port 80 (#0) * Trying 174.142.163.250... * connected * Connected to azlyrics.com (174.142.163.250) port 80 (#0) > GET /lyrics/anthrax/madhouse.html HTTP/1.1 Host: azlyrics.com Accept: */* < HTTP/1.1 301 Moved Permanently < Server: nginx/1.0.12 < Date: Thu, 05 Jul 2012 16:59:21 GMT < Content-Type: text/html < Content-Length: 185 < Connection: keep-alive < Location: http://www.azlyrics.com/lyrics/anthrax/madhouse.html < Segmentation fault Strangely, the file is there. The same error is displayed when there's no such page (redirect to azlyrics.com mainpage) What am I doing wrong? Thanks in advance EDIT: I made the function for writing data static, but this changes nothing. Even wget seems to have problems $ wget http://www.azlyrics.com/lyrics/anthrax/madhouse.html --2012-07-06 10:36:05-- http://www.azlyrics.com/lyrics/anthrax/madhouse.html Resolving www.azlyrics.com... 174.142.163.250 Connecting to www.azlyrics.com|174.142.163.250|:80... connected. HTTP request sent, awaiting response... No data received. Retrying. Why does opening the page in a browser work and wget/curl not? EDIT2: After adding this: curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1); The log is: * About to connect() to azlyrics.com port 80 (#0) * Trying 174.142.163.250... * connected * Connected to azlyrics.com (174.142.163.250) port 80 (#0) > GET /lyrics/anthrax/madhouse.html HTTP/1.1 Host: azlyrics.com Accept: */* < HTTP/1.1 301 Moved Permanently < Server: nginx/1.0.12 < Date: Fri, 06 Jul 2012 09:09:47 GMT < Content-Type: text/html < Content-Length: 185 < Connection: keep-alive < Location: http://www.azlyrics.com/lyrics/anthrax/madhouse.html < * Ignoring the response-body * Connection #0 to host azlyrics.com left intact * Issue another request to this URL: 'http://www.azlyrics.com/lyrics/anthrax/madhouse.html' * About to connect() to www.azlyrics.com port 80 (#1) * Trying 174.142.163.250... * connected * Connected to www.azlyrics.com (174.142.163.250) port 80 (#1) > GET /lyrics/anthrax/madhouse.html HTTP/1.1 Host: www.azlyrics.com Accept: */* < HTTP/1.1 200 OK < Server: nginx/1.0.12 < Date: Fri, 06 Jul 2012 09:09:47 GMT < Content-Type: text/html < Transfer-Encoding: chunked < Connection: keep-alive < Segmentation fault

    Read the article

  • F# numeric associations

    - by b1g3ar5
    I have a numeric association for a custom type as follows: let DiffNumerics = { new INumeric<Diff> with member op.Zero = C 0.0 member op.One = C 1.0 member op.Add(a,b) = a + b member op.Subtract(a,b) = a - b member op.Multiply(a,b) = a * b member ops.Negate(a) = Diff.negate a member ops.Abs(a) = Diff.abs a member ops.Equals(a, b) = ((=) a b) member ops.Compare(a, b) = Diff.compare a b member ops.Sign(a) = int (Diff.sign a).Val member ops.ToString(x,fmt,fmtprovider) = failwith "not implemented" member ops.Parse(s,numstyle,fmtprovider) = failwith "not implemented" } GlobalAssociations.RegisterNumericAssociation(DiffNumerics) It works fine in f# interactive, but crashes when I run, because .ElementOps is not filled correctly for a matrix of these types. Any ideas why this might be? EDIT: In fsi, the code let A = dmatrix [[Diff.C 1.;Diff.C 2.;Diff.C 3.];[Diff.C 4.;Diff.C 5.;Diff.C 6.]] let B = matrix [[1.;2.;3.];[4.;5.;6.]] gives: > A.ElementOps;; val it : INumeric<Diff> = FSI_0003.NewAD+DiffNumerics@258 > B.ElementOps;; val it : INumeric<float> = Microsoft.FSharp.Math.Instances+FloatNumerics@115 > in the debugger A.ElementOps shows: '(A).ElementOps' threw an exception of type 'System.NotSupportedException' and, for the B matrix: Microsoft.FSharp.Math.Instances+FloatNumerics@115 So somehow the DiffNumerics isn't making it to the compiled program.

    Read the article

  • Will Emacs --batch run in cron will hang when require user input?

    - by J Spen
    I have a job in crontab that requires emacs --batch but if the file is currently open it requests (s, p, q) to (steal, quit, etc...) which is fine if this file is being edited to not run the script but I want to make sure it kills the cron running script so it's not sitting in the background taking up memory. I have the output set to go to a log file so I can see this happening but no way to tell whether the script was terminated even though asked for user input. Does cron terminate these scripts and how to check the PID to make sure?

    Read the article

  • How to implement GCM in Google AppEngine?

    - by Broken System
    I'm a PHP Developer and Web Designer. In my work a partner asked me if I could set up a Google Cloud Messaging server. I read the documentation but couldn't find a clear tutorial to set up this server. I got no knowleadge about Java so it makes my job harder. I could "compile" a war file using ant as GCM Demo Tutorial says. But I can't deploy it to my AppEngine server to try it out (It's my first time using AppEngine too). Could you give me some steps to create my own GCM server? Sorry about my bad english. Thanks!

    Read the article

  • MVC 3 Remote Validation jQuery error on submit

    - by Richard Reddy
    I seem to have a weird issue with remote validation on my project. I am doing a simple validation check on an email field to ensure that it is unique. I've noticed that unless I put the cursor into the textbox and then remove it to trigger the validation at least once before submitting my form I will get a javascript error. e[h] is not a function jquery.min.js line 3 If I try to resubmit the form after the above error is returned everything works as expected. It's almost like the form tried to submit before waiting for the validation to return or something. Am I required to silently fire off a remote validation request on submit before submitting my form? Below is a snapshot of the code I'm using: (I've also tried GET instead of POST but I get the same result). As mentioned above, the code works fine but the form returns a jquery error unless the validation is triggered at least once. Model: public class RegisterModel { [Required] [Remote("DoesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name taken.")] [Display(Name = "User name")] public string UserName { get; set; } [Required] [Display(Name = "Firstname")] public string Firstname { get; set; } [Display(Name = "Surname")] public string Surname { get; set; } [Required] [Remote("DoesEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "Email taken.", AdditionalFields = "UserName")] [Display(Name = "Email address")] public string Email { get; set; } [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)] [DataType(DataType.Password)] [Display(Name = "Confirm password")] public string ConfirmPassword { get; set; } [Display(Name = "Approved?")] public bool IsApproved { get; set; } } public class UserRoleModel { [Display(Name = "Assign Roles")] public IEnumerable<RoleViewModel> AllRoles { get; set; } public RegisterModel RegisterUser { get; set; } } Controller: // POST: /Account/DoesEmailExist // passing in username so that I can ignore the same email address for the same user on edit page [HttpPost] public JsonResult DoesEmailExist([Bind(Prefix = "RegisterUser.Email")]string Email, [Bind(Prefix = "RegisterUser.UserName")]string UserName) { var user = Membership.GetUserNameByEmail(Email); if (!String.IsNullOrEmpty(UserName)) { if (user == UserName) return Json(true); } return Json(user == null); } View: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js" type="text/javascript"></script> <script type="text/javascript" src="/Content/web/js/jquery.unobtrusive-ajax.min.js"></script> <script type="text/javascript" src="/Content/web/js/jquery.validate.min.js"></script> <script type="text/javascript" src="/Content/web/js/jquery.validate.unobtrusive.min.js"></script> ...... @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="titleh"> <h3>Edit a user account</h3> </div> <div class="body"> @Html.HiddenFor(model => model.RegisterUser.UserName) @Html.Partial("_CreateOrEdit", Model) <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(model => model.RegisterUser.IsApproved)</span> @Html.RadioButtonFor(model => model.RegisterUser.IsApproved, true, new { @class = "uniform" }) Active @Html.RadioButtonFor(model => model.RegisterUser.IsApproved, false, new { @class = "uniform" }) Disabled <div class="clear"></div> </div> <div class="button-box"> <input type="submit" name="submit" value="Save" class="st-button"/> @Html.ActionLink("Back to List", "Index", null, new { @class = "st-clear" }) </div> </div> } CreateEdit Partial View @model Project.Domain.Entities.UserRoleModel <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(m => m.RegisterUser.Firstname)</span> @Html.TextBoxFor(m => m.RegisterUser.Firstname, new { @class = "st-forminput", @style = "width:300px" }) @Html.ValidationMessageFor(m => m.RegisterUser.Firstname) <div class="clear"></div> </div> <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(m => m.RegisterUser.Surname)</span> @Html.TextBoxFor(m => m.RegisterUser.Surname, new { @class = "st-forminput", @style = "width:300px" }) @Html.ValidationMessageFor(m => m.RegisterUser.Surname) <div class="clear"></div> </div> <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(m => m.RegisterUser.Email)</span> @Html.TextBoxFor(m => m.RegisterUser.Email, new { @class = "st-forminput", @style = "width:300px" }) @Html.ValidationMessageFor(m => m.RegisterUser.Email) <div class="clear"></div> </div> Thanks, Rich

    Read the article

  • Segue Popover won't behave properly

    - by CStreel
    I'm trying to use Segue to present then dismiss a Popover view a UIBarButtonItem is clicked. I've created a generic Segue that is not anchored to anything but the view and given it a name I've Anchored the UIBarButtonItem in the Interface Builder to: - (IBAction)clickedSettings:(id)sender { if(self.popSegue != nil) { [self.popSegue.popoverController dismissPopoverAnimated:YES]; } else { //Current says only a button may [self performSegueWithIdentifier:@"Settings" sender:sender]; } } But when ever i click the button to display the Segue it gives me an error: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UIStoryboardPopoverSegue must be presented from a bar button item or a view.' It doesn't even hit my -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender I've read the following questions on stack: iOS:How to dismiss Popover UIBarButtonItem + popover segue creates multiple popovers But i still get the same error. For the life of me i can't figure out what is going wrong

    Read the article

  • NHibernate Pitfalls: Lazy Scalar Properties Must Be Auto

    - by Ricardo Peres
    This is part of a series of posts about NHibernate Pitfalls. See the entire collection here. NHibernate supports lazy properties not just for associations (many to one, one to one, one to many, many to many) but also for scalar properties. This allows, for example, only loading a potentially large BLOB or CLOB from the database if and when it is necessary, that is, when the property is actually accessed. In order for this to work, other than having to be declared virtual, the property can’t have an explicitly declared backing field, it must be an auto property: 1: public virtual String MyLongTextProperty 2: { 3: get; 4: set; 5: } 6:  7: public virtual Byte [] MyLongPictureProperty 8: { 9: get; 10: set; 11: } All lazy scalar properties are retrieved at the same time, when one of them is accessed.

    Read the article

  • Vote of Disconfidence to Entity Framework

    - by Ricardo Peres
    A friend of mine has found the following problem with Entity Framework 4: Two simple classes and one association between them (one to many): One condition to filter out soft-deleted entities (WHERE Deleted = 0): 100 records in the database; A simple query: 1: var l = ctx.Person.Include("Address").Where(x => (x.Address.Name == "317 Oak Blvd." && x.Address.Number == 926) || (x.Address.Name == "891 White Milton Drive" && x.Address.Number == 497)); Will produce the following SQL: 1: SELECT 2: [Extent1].[Id] AS [Id], 3: [Extent1].[FullName] AS [FullName], 4: [Extent1].[AddressId] AS [AddressId], 5: [Extent202].[Id] AS [Id1], 6: [Extent202].[Name] AS [Name], 7: [Extent202].[Number] AS [Number] 8: FROM [dbo].[Person] AS [Extent1] 9: LEFT OUTER JOIN [dbo].[Address] AS [Extent2] ON ([Extent2].[Deleted] = 0) AND ([Extent1].[AddressId] = [Extent2].[Id]) 10: LEFT OUTER JOIN [dbo].[Address] AS [Extent3] ON ([Extent3].[Deleted] = 0) AND ([Extent1].[AddressId] = [Extent3].[Id]) 11: LEFT OUTER JOIN [dbo].[Address] AS [Extent4] ON ([Extent4].[Deleted] = 0) AND ([Extent1].[AddressId] = [Extent4].[Id]) 12: LEFT OUTER JOIN [dbo].[Address] AS [Extent5] ON ([Extent5].[Deleted] = 0) AND ([Extent1].[AddressId] = [Extent5].[Id]) 13: LEFT OUTER JOIN [dbo].[Address] AS [Extent6] ON ([Extent6].[Deleted] = 0) AND ([Extent1].[AddressId] = [Extent6].[Id]) 14: ... 15: WHERE ((N'317 Oak Blvd.' = [Extent2].[Name]) AND (926 = [Extent3].[Number])) 16: ... And will result in 680 MB of memory being taken! Now, Entity Framework has been historically known for producing less than optimal SQL, but 680 MB for 100 entities?! According to Microsoft, the problem will be addressed in the following version, there is a Connect issue open. There is even a whitepaper, Performance Considerations for Entity Framework 5, which talks about some of the changes and optimizations coming on version 5, but by reading it, I got even more concerned: “Once the cache contains a set number of entries (800), we start a timer that periodically (once-per-minute) sweeps the cache.” Say what?! The next version of Entity Framework will spawn timer threads?! When Code First came along, I thought it was a step in the right direction. Sure, it didn’t include some things that NHibernate did for quite some time – for example, different strategies for Id generation that do not rely on IDENTITY columns, which makes INSERT batching impossible, or support for enumerated types – but I thought these would come with the time. Now, enumerated types have, but so did… timer threads! I’m afraid Entity Framework is becoming a monster.

    Read the article

  • Service Discovery in WCF 4.0 &ndash; Part 1

    - by Shaun
    When designing a service oriented architecture (SOA) system, there will be a lot of services with many service contracts, endpoints and behaviors. Besides the client calling the service, in a large distributed system a service may invoke other services. In this case, one service might need to know the endpoints it invokes. This might not be a problem in a small system. But when you have more than 10 services this might be a problem. For example in my current product, there are around 10 services, such as the user authentication service, UI integration service, location service, license service, device monitor service, event monitor service, schedule job service, accounting service, player management service, etc..   Benefit of Discovery Service Since almost all my services need to invoke at least one other service. This would be a difficult task to make sure all services endpoints are configured correctly in every service. And furthermore, it would be a nightmare when a service changed its endpoint at runtime. Hence, we need a discovery service to remove the dependency (configuration dependency). A discovery service plays as a service dictionary which stores the relationship between the contracts and the endpoints for every service. By using the discovery service, when service X wants to invoke service Y, it just need to ask the discovery service where is service Y, then the discovery service will return all proper endpoints of service Y, then service X can use the endpoint to send the request to service Y. And when some services changed their endpoint address, all need to do is to update its records in the discovery service then all others will know its new endpoint. In WCF 4.0 Discovery it supports both managed proxy discovery mode and ad-hoc discovery mode. In ad-hoc mode there is no standalone discovery service. When a client wanted to invoke a service, it will broadcast an message (normally in UDP protocol) to the entire network with the service match criteria. All services which enabled the discovery behavior will receive this message and only those matched services will send their endpoint back to the client. The managed proxy discovery service works as I described above. In this post I will only cover the managed proxy mode, where there’s a discovery service. For more information about the ad-hoc mode please refer to the MSDN.   Service Announcement and Probe The main functionality of discovery service should be return the proper endpoint addresses back to the service who is looking for. In most cases the consume service (as a client) will send the contract which it wanted to request to the discovery service. And then the discovery service will find the endpoint and respond. Sometimes the contract and endpoint are not enough. It also contains versioning, extensions attributes. This post I will only cover the case includes contract and endpoint. When a client (or sometimes a service who need to invoke another service) need to connect to a target service, it will firstly request the discovery service through the “Probe” method with the criteria. Basically the criteria contains the contract type name of the target service. Then the discovery service will search its endpoint repository by the criteria. The repository might be a database, a distributed cache or a flat XML file. If it matches, the discovery service will grab the endpoint information (it’s called discovery endpoint metadata in WCF) and send back. And this is called “Probe”. Finally the client received the discovery endpoint metadata and will use the endpoint to connect to the target service. Besides the probe, discovery service should take the responsible to know there is a new service available when it goes online, as well as stopped when it goes offline. This feature is named “Announcement”. When a service started and stopped, it will announce to the discovery service. So the basic functionality of a discovery service should includes: 1, An endpoint which receive the service online message, and add the service endpoint information in the discovery repository. 2, An endpoint which receive the service offline message, and remove the service endpoint information from the discovery repository. 3, An endpoint which receive the client probe message, and return the matches service endpoints, and return the discovery endpoint metadata. WCF 4.0 discovery service just covers all these features in it's infrastructure classes.   Discovery Service in WCF 4.0 WCF 4.0 introduced a new assembly named System.ServiceModel.Discovery which has all necessary classes and interfaces to build a WS-Discovery compliant discovery service. It supports ad-hoc and managed proxy modes. For the case mentioned in this post, what we need to build is a standalone discovery service, which is the managed proxy discovery service mode. To build a managed discovery service in WCF 4.0 just create a new class inherits from the abstract class System.ServiceModel.Discovery.DiscoveryProxy. This class implemented and abstracted the procedures of service announcement and probe. And it exposes 8 abstract methods where we can implement our own endpoint register, unregister and find logic. These 8 methods are asynchronized, which means all invokes to the discovery service are asynchronously, for better service capability and performance. 1, OnBeginOnlineAnnouncement, OnEndOnlineAnnouncement: Invoked when a service sent the online announcement message. We need to add the endpoint information to the repository in this method. 2, OnBeginOfflineAnnouncement, OnEndOfflineAnnouncement: Invoked when a service sent the offline announcement message. We need to remove the endpoint information from the repository in this method. 3, OnBeginFind, OnEndFind: Invoked when a client sent the probe message that want to find the service endpoint information. We need to look for the proper endpoints by matching the client’s criteria through the repository in this method. 4, OnBeginResolve, OnEndResolve: Invoked then a client sent the resolve message. Different from the find method, when using resolve method the discovery service will return the exactly one service endpoint metadata to the client. In our example we will NOT implement this method.   Let’s create our own discovery service, inherit the base System.ServiceModel.Discovery.DiscoveryProxy. We also need to specify the service behavior in this class. Since the build-in discovery service host class only support the singleton mode, we must set its instance context mode to single. 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.ServiceModel.Discovery; 6: using System.ServiceModel; 7:  8: namespace Phare.Service 9: { 10: [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] 11: public class ManagedProxyDiscoveryService : DiscoveryProxy 12: { 13: protected override IAsyncResult OnBeginFind(FindRequestContext findRequestContext, AsyncCallback callback, object state) 14: { 15: throw new NotImplementedException(); 16: } 17:  18: protected override IAsyncResult OnBeginOfflineAnnouncement(DiscoveryMessageSequence messageSequence, EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, object state) 19: { 20: throw new NotImplementedException(); 21: } 22:  23: protected override IAsyncResult OnBeginOnlineAnnouncement(DiscoveryMessageSequence messageSequence, EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, object state) 24: { 25: throw new NotImplementedException(); 26: } 27:  28: protected override IAsyncResult OnBeginResolve(ResolveCriteria resolveCriteria, AsyncCallback callback, object state) 29: { 30: throw new NotImplementedException(); 31: } 32:  33: protected override void OnEndFind(IAsyncResult result) 34: { 35: throw new NotImplementedException(); 36: } 37:  38: protected override void OnEndOfflineAnnouncement(IAsyncResult result) 39: { 40: throw new NotImplementedException(); 41: } 42:  43: protected override void OnEndOnlineAnnouncement(IAsyncResult result) 44: { 45: throw new NotImplementedException(); 46: } 47:  48: protected override EndpointDiscoveryMetadata OnEndResolve(IAsyncResult result) 49: { 50: throw new NotImplementedException(); 51: } 52: } 53: } Then let’s implement the online, offline and find methods one by one. WCF discovery service gives us full flexibility to implement the endpoint add, remove and find logic. For the demo purpose we will use an internal dictionary to store the services’ endpoint metadata. In the next post we will see how to serialize and store these information in database. Define a concurrent dictionary inside the service class since our it will be used in the multiple threads scenario. 1: [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] 2: public class ManagedProxyDiscoveryService : DiscoveryProxy 3: { 4: private ConcurrentDictionary<EndpointAddress, EndpointDiscoveryMetadata> _services; 5:  6: public ManagedProxyDiscoveryService() 7: { 8: _services = new ConcurrentDictionary<EndpointAddress, EndpointDiscoveryMetadata>(); 9: } 10: } Then we can simply implement the logic of service online and offline. 1: protected override IAsyncResult OnBeginOnlineAnnouncement(DiscoveryMessageSequence messageSequence, EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, object state) 2: { 3: _services.AddOrUpdate(endpointDiscoveryMetadata.Address, endpointDiscoveryMetadata, (key, value) => endpointDiscoveryMetadata); 4: return new OnOnlineAnnouncementAsyncResult(callback, state); 5: } 6:  7: protected override void OnEndOnlineAnnouncement(IAsyncResult result) 8: { 9: OnOnlineAnnouncementAsyncResult.End(result); 10: } 11:  12: protected override IAsyncResult OnBeginOfflineAnnouncement(DiscoveryMessageSequence messageSequence, EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, object state) 13: { 14: EndpointDiscoveryMetadata endpoint = null; 15: _services.TryRemove(endpointDiscoveryMetadata.Address, out endpoint); 16: return new OnOfflineAnnouncementAsyncResult(callback, state); 17: } 18:  19: protected override void OnEndOfflineAnnouncement(IAsyncResult result) 20: { 21: OnOfflineAnnouncementAsyncResult.End(result); 22: } Regards the find method, the parameter FindRequestContext.Criteria has a method named IsMatch, which can be use for us to evaluate which service metadata is satisfied with the criteria. So the implementation of find method would be like this. 1: protected override IAsyncResult OnBeginFind(FindRequestContext findRequestContext, AsyncCallback callback, object state) 2: { 3: _services.Where(s => findRequestContext.Criteria.IsMatch(s.Value)) 4: .Select(s => s.Value) 5: .All(meta => 6: { 7: findRequestContext.AddMatchingEndpoint(meta); 8: return true; 9: }); 10: return new OnFindAsyncResult(callback, state); 11: } 12:  13: protected override void OnEndFind(IAsyncResult result) 14: { 15: OnFindAsyncResult.End(result); 16: } As you can see, we checked all endpoints metadata in repository by invoking the IsMatch method. Then add all proper endpoints metadata into the parameter. Finally since all these methods are asynchronized we need some AsyncResult classes as well. Below are the base class and the inherited classes used in previous methods. 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.Threading; 6:  7: namespace Phare.Service 8: { 9: abstract internal class AsyncResult : IAsyncResult 10: { 11: AsyncCallback callback; 12: bool completedSynchronously; 13: bool endCalled; 14: Exception exception; 15: bool isCompleted; 16: ManualResetEvent manualResetEvent; 17: object state; 18: object thisLock; 19:  20: protected AsyncResult(AsyncCallback callback, object state) 21: { 22: this.callback = callback; 23: this.state = state; 24: this.thisLock = new object(); 25: } 26:  27: public object AsyncState 28: { 29: get 30: { 31: return state; 32: } 33: } 34:  35: public WaitHandle AsyncWaitHandle 36: { 37: get 38: { 39: if (manualResetEvent != null) 40: { 41: return manualResetEvent; 42: } 43: lock (ThisLock) 44: { 45: if (manualResetEvent == null) 46: { 47: manualResetEvent = new ManualResetEvent(isCompleted); 48: } 49: } 50: return manualResetEvent; 51: } 52: } 53:  54: public bool CompletedSynchronously 55: { 56: get 57: { 58: return completedSynchronously; 59: } 60: } 61:  62: public bool IsCompleted 63: { 64: get 65: { 66: return isCompleted; 67: } 68: } 69:  70: object ThisLock 71: { 72: get 73: { 74: return this.thisLock; 75: } 76: } 77:  78: protected static TAsyncResult End<TAsyncResult>(IAsyncResult result) 79: where TAsyncResult : AsyncResult 80: { 81: if (result == null) 82: { 83: throw new ArgumentNullException("result"); 84: } 85:  86: TAsyncResult asyncResult = result as TAsyncResult; 87:  88: if (asyncResult == null) 89: { 90: throw new ArgumentException("Invalid async result.", "result"); 91: } 92:  93: if (asyncResult.endCalled) 94: { 95: throw new InvalidOperationException("Async object already ended."); 96: } 97:  98: asyncResult.endCalled = true; 99:  100: if (!asyncResult.isCompleted) 101: { 102: asyncResult.AsyncWaitHandle.WaitOne(); 103: } 104:  105: if (asyncResult.manualResetEvent != null) 106: { 107: asyncResult.manualResetEvent.Close(); 108: } 109:  110: if (asyncResult.exception != null) 111: { 112: throw asyncResult.exception; 113: } 114:  115: return asyncResult; 116: } 117:  118: protected void Complete(bool completedSynchronously) 119: { 120: if (isCompleted) 121: { 122: throw new InvalidOperationException("This async result is already completed."); 123: } 124:  125: this.completedSynchronously = completedSynchronously; 126:  127: if (completedSynchronously) 128: { 129: this.isCompleted = true; 130: } 131: else 132: { 133: lock (ThisLock) 134: { 135: this.isCompleted = true; 136: if (this.manualResetEvent != null) 137: { 138: this.manualResetEvent.Set(); 139: } 140: } 141: } 142:  143: if (callback != null) 144: { 145: callback(this); 146: } 147: } 148:  149: protected void Complete(bool completedSynchronously, Exception exception) 150: { 151: this.exception = exception; 152: Complete(completedSynchronously); 153: } 154: } 155: } 1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Text; 5: using System.ServiceModel.Discovery; 6: using Phare.Service; 7:  8: namespace Phare.Service 9: { 10: internal sealed class OnOnlineAnnouncementAsyncResult : AsyncResult 11: { 12: public OnOnlineAnnouncementAsyncResult(AsyncCallback callback, object state) 13: : base(callback, state) 14: { 15: this.Complete(true); 16: } 17:  18: public static void End(IAsyncResult result) 19: { 20: AsyncResult.End<OnOnlineAnnouncementAsyncResult>(result); 21: } 22:  23: } 24:  25: sealed class OnOfflineAnnouncementAsyncResult : AsyncResult 26: { 27: public OnOfflineAnnouncementAsyncResult(AsyncCallback callback, object state) 28: : base(callback, state) 29: { 30: this.Complete(true); 31: } 32:  33: public static void End(IAsyncResult result) 34: { 35: AsyncResult.End<OnOfflineAnnouncementAsyncResult>(result); 36: } 37: } 38:  39: sealed class OnFindAsyncResult : AsyncResult 40: { 41: public OnFindAsyncResult(AsyncCallback callback, object state) 42: : base(callback, state) 43: { 44: this.Complete(true); 45: } 46:  47: public static void End(IAsyncResult result) 48: { 49: AsyncResult.End<OnFindAsyncResult>(result); 50: } 51: } 52:  53: sealed class OnResolveAsyncResult : AsyncResult 54: { 55: EndpointDiscoveryMetadata matchingEndpoint; 56:  57: public OnResolveAsyncResult(EndpointDiscoveryMetadata matchingEndpoint, AsyncCallback callback, object state) 58: : base(callback, state) 59: { 60: this.matchingEndpoint = matchingEndpoint; 61: this.Complete(true); 62: } 63:  64: public static EndpointDiscoveryMetadata End(IAsyncResult result) 65: { 66: OnResolveAsyncResult thisPtr = AsyncResult.End<OnResolveAsyncResult>(result); 67: return thisPtr.matchingEndpoint; 68: } 69: } 70: } Now we have finished the discovery service. The next step is to host it. The discovery service is a standard WCF service. So we can use ServiceHost on a console application, windows service, or in IIS as usual. The following code is how to host the discovery service we had just created in a console application. 1: static void Main(string[] args) 2: { 3: using (var host = new ServiceHost(new ManagedProxyDiscoveryService())) 4: { 5: host.Opened += (sender, e) => 6: { 7: host.Description.Endpoints.All((ep) => 8: { 9: Console.WriteLine(ep.ListenUri); 10: return true; 11: }); 12: }; 13:  14: try 15: { 16: // retrieve the announcement, probe endpoint and binding from configuration 17: var announcementEndpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["announcementEndpointAddress"]); 18: var probeEndpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["probeEndpointAddress"]); 19: var binding = Activator.CreateInstance(Type.GetType(ConfigurationManager.AppSettings["bindingType"], true, true)) as Binding; 20: var announcementEndpoint = new AnnouncementEndpoint(binding, announcementEndpointAddress); 21: var probeEndpoint = new DiscoveryEndpoint(binding, probeEndpointAddress); 22: probeEndpoint.IsSystemEndpoint = false; 23: // append the service endpoint for announcement and probe 24: host.AddServiceEndpoint(announcementEndpoint); 25: host.AddServiceEndpoint(probeEndpoint); 26:  27: host.Open(); 28:  29: Console.WriteLine("Press any key to exit."); 30: Console.ReadKey(); 31: } 32: catch (Exception ex) 33: { 34: Console.WriteLine(ex.ToString()); 35: } 36: } 37:  38: Console.WriteLine("Done."); 39: Console.ReadKey(); 40: } What we need to notice is that, the discovery service needs two endpoints for announcement and probe. In this example I just retrieve them from the configuration file. I also specified the binding of these two endpoints in configuration file as well. 1: <?xml version="1.0"?> 2: <configuration> 3: <startup> 4: <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> 5: </startup> 6: <appSettings> 7: <add key="announcementEndpointAddress" value="net.tcp://localhost:10010/announcement"/> 8: <add key="probeEndpointAddress" value="net.tcp://localhost:10011/probe"/> 9: <add key="bindingType" value="System.ServiceModel.NetTcpBinding, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> 10: </appSettings> 11: </configuration> And this is the console screen when I ran my discovery service. As you can see there are two endpoints listening for announcement message and probe message.   Discoverable Service and Client Next, let’s create a WCF service that is discoverable, which means it can be found by the discovery service. To do so, we need to let the service send the online announcement message to the discovery service, as well as offline message before it shutdown. Just create a simple service which can make the incoming string to upper. The service contract and implementation would be like this. 1: [ServiceContract] 2: public interface IStringService 3: { 4: [OperationContract] 5: string ToUpper(string content); 6: } 1: public class StringService : IStringService 2: { 3: public string ToUpper(string content) 4: { 5: return content.ToUpper(); 6: } 7: } Then host this service in the console application. In order to make the discovery service easy to be tested the service address will be changed each time it’s started. 1: static void Main(string[] args) 2: { 3: var baseAddress = new Uri(string.Format("net.tcp://localhost:11001/stringservice/{0}/", Guid.NewGuid().ToString())); 4:  5: using (var host = new ServiceHost(typeof(StringService), baseAddress)) 6: { 7: host.Opened += (sender, e) => 8: { 9: Console.WriteLine("Service opened at {0}", host.Description.Endpoints.First().ListenUri); 10: }; 11:  12: host.AddServiceEndpoint(typeof(IStringService), new NetTcpBinding(), string.Empty); 13:  14: host.Open(); 15:  16: Console.WriteLine("Press any key to exit."); 17: Console.ReadKey(); 18: } 19: } Currently this service is NOT discoverable. We need to add a special service behavior so that it could send the online and offline message to the discovery service announcement endpoint when the host is opened and closed. WCF 4.0 introduced a service behavior named ServiceDiscoveryBehavior. When we specified the announcement endpoint address and appended it to the service behaviors this service will be discoverable. 1: var announcementAddress = new EndpointAddress(ConfigurationManager.AppSettings["announcementEndpointAddress"]); 2: var announcementBinding = Activator.CreateInstance(Type.GetType(ConfigurationManager.AppSettings["bindingType"], true, true)) as Binding; 3: var announcementEndpoint = new AnnouncementEndpoint(announcementBinding, announcementAddress); 4: var discoveryBehavior = new ServiceDiscoveryBehavior(); 5: discoveryBehavior.AnnouncementEndpoints.Add(announcementEndpoint); 6: host.Description.Behaviors.Add(discoveryBehavior); The ServiceDiscoveryBehavior utilizes the service extension and channel dispatcher to implement the online and offline announcement logic. In short, it injected the channel open and close procedure and send the online and offline message to the announcement endpoint.   On client side, when we have the discovery service, a client can invoke a service without knowing its endpoint. WCF discovery assembly provides a class named DiscoveryClient, which can be used to find the proper service endpoint by passing the criteria. In the code below I initialized the DiscoveryClient, specified the discovery service probe endpoint address. Then I created the find criteria by specifying the service contract I wanted to use and invoke the Find method. This will send the probe message to the discovery service and it will find the endpoints back to me. The discovery service will return all endpoints that matches the find criteria, which means in the result of the find method there might be more than one endpoints. In this example I just returned the first matched one back. In the next post I will show how to extend our discovery service to make it work like a service load balancer. 1: static EndpointAddress FindServiceEndpoint() 2: { 3: var probeEndpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["probeEndpointAddress"]); 4: var probeBinding = Activator.CreateInstance(Type.GetType(ConfigurationManager.AppSettings["bindingType"], true, true)) as Binding; 5: var discoveryEndpoint = new DiscoveryEndpoint(probeBinding, probeEndpointAddress); 6:  7: EndpointAddress address = null; 8: FindResponse result = null; 9: using (var discoveryClient = new DiscoveryClient(discoveryEndpoint)) 10: { 11: result = discoveryClient.Find(new FindCriteria(typeof(IStringService))); 12: } 13:  14: if (result != null && result.Endpoints.Any()) 15: { 16: var endpointMetadata = result.Endpoints.First(); 17: address = endpointMetadata.Address; 18: } 19: return address; 20: } Once we probed the discovery service we will receive the endpoint. So in the client code we can created the channel factory from the endpoint and binding, and invoke to the service. When creating the client side channel factory we need to make sure that the client side binding should be the same as the service side. WCF discovery service can be used to find the endpoint for a service contract, but the binding is NOT included. This is because the binding was not in the WS-Discovery specification. In the next post I will demonstrate how to add the binding information into the discovery service. At that moment the client don’t need to create the binding by itself. Instead it will use the binding received from the discovery service. 1: static void Main(string[] args) 2: { 3: Console.WriteLine("Say something..."); 4: var content = Console.ReadLine(); 5: while (!string.IsNullOrWhiteSpace(content)) 6: { 7: Console.WriteLine("Finding the service endpoint..."); 8: var address = FindServiceEndpoint(); 9: if (address == null) 10: { 11: Console.WriteLine("There is no endpoint matches the criteria."); 12: } 13: else 14: { 15: Console.WriteLine("Found the endpoint {0}", address.Uri); 16:  17: var factory = new ChannelFactory<IStringService>(new NetTcpBinding(), address); 18: factory.Opened += (sender, e) => 19: { 20: Console.WriteLine("Connecting to {0}.", factory.Endpoint.ListenUri); 21: }; 22: var proxy = factory.CreateChannel(); 23: using (proxy as IDisposable) 24: { 25: Console.WriteLine("ToUpper: {0} => {1}", content, proxy.ToUpper(content)); 26: } 27: } 28:  29: Console.WriteLine("Say something..."); 30: content = Console.ReadLine(); 31: } 32: } Similarly, the discovery service probe endpoint and binding were defined in the configuration file. 1: <?xml version="1.0"?> 2: <configuration> 3: <startup> 4: <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> 5: </startup> 6: <appSettings> 7: <add key="announcementEndpointAddress" value="net.tcp://localhost:10010/announcement"/> 8: <add key="probeEndpointAddress" value="net.tcp://localhost:10011/probe"/> 9: <add key="bindingType" value="System.ServiceModel.NetTcpBinding, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> 10: </appSettings> 11: </configuration> OK, now let’s have a test. Firstly start the discovery service, and then start our discoverable service. When it started it will announced to the discovery service and registered its endpoint into the repository, which is the local dictionary. And then start the client and type something. As you can see the client asked the discovery service for the endpoint and then establish the connection to the discoverable service. And more interesting, do NOT close the client console but terminate the discoverable service but press the enter key. This will make the service send the offline message to the discovery service. Then start the discoverable service again. Since we made it use a different address each time it started, currently it should be hosted on another address. If we enter something in the client we could see that it asked the discovery service and retrieve the new endpoint, and connect the the service.   Summary In this post I discussed the benefit of using the discovery service and the procedures of service announcement and probe. I also demonstrated how to leverage the WCF Discovery feature in WCF 4.0 to build a simple managed discovery service. For test purpose, in this example I used the in memory dictionary as the discovery endpoint metadata repository. And when finding I also just return the first matched endpoint back. I also hard coded the bindings between the discoverable service and the client. In next post I will show you how to solve the problem mentioned above, as well as some additional feature for production usage. You can download the code here.   Hope this helps, Shaun All documents and related graphics, codes are provided "AS IS" without warranty of any kind. Copyright © Shaun Ziyan Xu. This work is licensed under the Creative Commons License.

    Read the article

  • Free book from Microsoft on on Office 365

    - by TATWORTH
    At http://blogs.msdn.com/b/microsoft_press/archive/2011/08/17/free-ebook-microsoft-office-365-connect-and-collaborate-virtually-anywhere-anytime.aspx  you can get a free book from Microsoft on Office 365 (Epub and mobi formats are available at http://blogs.msdn.com/b/microsoft_press/archive/2011/09/23/free-ebook-microsoft-office-365-connect-and-collaborate-virtually-anywhere-anytime-now-in-more-formats.aspx)

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >