A misbehaving WCF service asynch call - wcf

Okay, I have a WCF service which is going to be acting as a way to access my SQL database. That part has become largely irrelevant to this question, since for some reason my WCF service crashes. Or, at least, it causes my client Silverlight application to crash. This is why I come here to ask you guys about it.
So here's the code. Bear in mind that it is called asynchronously from my Silverlight client. When it is done, the string that is returned from this method is put on the screen for the client.
public string AddClients(IEnumerable<Client> newClients)
{
int nAdded = 0;
int nelse = 0;
string str = "";
List<Client> newClientsList = newClients.ToList();
List<Client> existingClients = dc.Clients.ToList();
List<Client> clientsToAdd = new List<Client>();
return newClientsList.Count.ToString();
foreach (Client client in newClientsList)
{
var clt = existingClients.FirstOrDefault(c => c.ClientName == client.ClientName);
if (clt == null)
{
return clt.ClientName;
//str = str + " found: " + clt.ClientName + "\n";
//dc.Clients.(clt);
//existingClients.Add(clt);
// clientsToAdd.Add(clt);
nAdded++;
}
else
{
nelse++;
}
}
if (nAdded > 0)
{
//str = str + " more than one nAdded";
// dc.Clients.InsertAllOnSubmit(clientsToAdd);
// dc.SubmitChanges();
}
return nelse.ToString();
}
You may be able to figure out what's supposed to be happening, but most of it's not happening now due to the fact that it's not working out for me very well.
At the moment, as you can see, there is a return quite early on (before the foreach). With things as they are, that works okay. You press a button in the client, it makes the call, and then returns. So as it is, you get '3' returned as a string (this is the size of newClients, the parameter). That is okay, and at least proves that the service can be connected to, that it returns messages okay, and what not.
If I remove that top most return, this is where it gets interesting (well, problematic). It should either return clt.ClientName, in the if (clt==null) condition, or it should return nelse.ToString() which is right at the end.
What do I actually get? Nothing. The method for the completion never seems to get called (the message box it shows never appears).
I've commented most of the stuff out. Surely it has to get to one of these conditions! Have I missed something really obvious here? I really have been attempting to debug this for ages, but nothing! Can someone see something obvious that I can't see?
For the record, 'dc' is the data context, and dc.Clients is a list of Client entities.

I could be missing something, but won't this throw a NullReferenceException? That has to be at least part of your problem.
if (clt == null)
{
return clt.ClientName;
...

I dont understand why you are trying to return the name of the first newly found client from the list you received. Why not just return an integer with total count of newly found clients that you are inserting in the database.
Try:
public string AddClients(IEnumerable<Client> newClients)
{
string str = "";
List<Client> newClientsList = newClients.ToList();
//to save processor and network
List<string> existingClients = dc.Clients.Select(x => x.ClientName).ToList();
List<Client> clientsToAdd = (from nc in newClientsList
join ec in existingClients on nc.ClientName equals ec into nec
from ec in nec.DefaultIfEmpty()
where ec == null
select nc).ToList();
if (clientsToAdd.Count > 0)
{
dc.Clients.InsertAllOnSubmit(clientsToAdd);
foreach (Client c in clientsToAdd)
str += "found: " + c.ClientName + "\n";
return str;
}
return "0 new clients found";
}
easier, simpler, cleaner.

Related

Insert Multiple records RIA services

I have a service class to hold the calls to the RIA service.
I have the following method to save multiple records, on the first step I should get the famous MaxId from the table and increment it in the foreach to add the objects.
public bool SaveRecs(ObservableCollection<Acc> accList)
{
int i = 0;
invokeOperation = Context.GetMaxAcc();
invokeOperation.Completed +=
(s, a) =>
{
foreach (Acc item in accList)
{
//if (CheckAcc(item.name, item.id)) continue;
item.id = invokeOperation.Value + i;
Context.Accs.Add(item);
i++;
}
};
return Commit();
}
The problem is that when the method is called first time, it do nothing and second time it works, the strange is that it may give an error of duplicate.
when I debug the code the id was ZERO
Is this the correct way of doing it?
thanks
My mistake, I should move the commit after the foreach.

Registering plugin on quick find in Dynamics CRM 2013

I have to register a plugin on Quick Find search on "Artilce" entity. When user enter any thing in quick find text box on Article entity at that time my plugin execute and return filter the data based on our business logic.
1.What event is fired when we find using quick find.
2.What message passes when this event is fired.
I have tried registering the plugin on RetrieveMultiple message but this is not triggered when we click on search in quick find.
Please help.
We have a Plugin registered on the RetrieveMultiple. We had a business requirement to search for the records, using WildCard by default.
Plugin Registration Details:
Message: RetrieveMultiple
Primary Entity:None
Secondary Entity:None
Pre-Operation
Code:
public const String QueryLiteral = "Query";
public const String LIKE = "%";
public void Execute(IServiceProvider serviceProvider)
{
String ParentEntity = String.Empty;
String OriginalSearch = String.Empty;
// Obtain the execution context from the service provider.
var ContextInstance = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// Get a reference to the Organization service.
IOrganizationService ServiceInstance =
((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).
CreateOrganizationService(ContextInstance.InitiatingUserId);
// Critical Point here - NOTICE that the InputParameters Contains the word Query
if (ContextInstance.Depth < 2 && ContextInstance.InputParameters.Contains(QueryLiteral) &&
ContextInstance.InputParameters[QueryLiteral] is QueryExpression)
{
QueryExpression QueryPointer = (ContextInstance.InputParameters[QueryLiteral] as QueryExpression);
//Verify the conversion worked as expected - if not, everything else is useless
if (null != QueryPointer)
{
// Check if the request is coming from any Search View
// We know this b/c Criteria isn't null and the Filters Count > 1
if (null != QueryPointer.Criteria && QueryPointer.Criteria.Filters.Count > 1)
{
ParentEntity = ContextInstance.PrimaryEntityName;
OriginalSearch = QueryPointer.Criteria.Filters[1].Conditions[0].Values[0].ToString();
OriginalSearch = String.Format(CultureInfo.CurrentCulture,
"{0}{1}", LIKE, OriginalSearch);
}
ConditionExpression NewCondition = null;
FilterExpression NewFilter = null;
if (null != QueryPointer.Criteria)
{
//Change the default 'BeginsWith'Operator to 'Contains/Like' operator in the basic search query
foreach (FilterExpression FilterSet in QueryPointer.Criteria.Filters)
{
foreach (ConditionExpression ConditionSet in FilterSet.Conditions)
{
if (ConditionSet.Operator == ConditionOperator.Like)
{
if (OriginalSearch != "")
ConditionSet.Values[0] = OriginalSearch;
else
{
OriginalSearch = QueryPointer.Criteria.Filters[0].Conditions[0].Values[0].ToString();
OriginalSearch = String.Format(CultureInfo.CurrentCulture,
"{0}{1}", LIKE, OriginalSearch);
ConditionSet.Values[0] = OriginalSearch;
}
}
}
}
}
}
ContextInstance.InputParameters[QueryLiteral] = QueryPointer;
}
}
Check details on this Post: http://www.williamgryan.mobi/?p=596
We have raised a ticket with Microsoft to address this situaation.
The solution they provided was to modify the Database to make the message
SearchByTitleKbArticleRequest available in the plugin registration tool.
I currently dont remember the table that we updated a flag against these messages.
After updating the table we were able to register the plugin against the message
SearchByTitleKbArticleRequest
Then the plugin triggered and we modified the entity collection returned from there.

Dapper.Net and the DataReader

I have a very strange error with dapper:
there is already an open DataReader associated with this Command
which must be closed first
But I don't use DataReader! I just call select query on my server application and take first result:
//How I run query:
public static T SelectVersion(IDbTransaction transaction = null)
{
return DbHelper.DataBase.Connection.Query<T>("SELECT * FROM [VersionLog] WHERE [Version] = (SELECT MAX([Version]) FROM [VersionLog])", null, transaction, commandTimeout: DbHelper.CommandTimeout).FirstOrDefault();
}
//And how I call this method:
public Response Upload(CommitRequest message) //It is calling on server from client
{
//Prepearing data from CommitRequest
using (var tr = DbHelper.DataBase.Connection.BeginTransaction(IsolationLevel.Serializable))
{
int v = SelectQueries<VersionLog>.SelectVersion(tr) != null ? SelectQueries<VersionLog>.SelectVersion(tr).Version : 0; //Call my query here
int newVersion = v + 1; //update version
//Saving changes from CommitRequest to db
//Updated version saving to base too, maybe it is problem?
return new Response
{
Message = String.Empty,
ServerBaseVersion = versionLog.Version,
};
}
}
}
And most sadly that this exception appearing in random time, I think what problem in concurrent access to server from two clients.
Please help.
This some times happens if the model and database schema are not matching and an exception is being raised inside Dapper.
If you really want to get into this, best way is to include dapper source in your project and debug.

How can I rotate back?

I am developing a wcf service for Windows 8 APP. But I'm choked up at one point.
The following method, it is coming data in the database using entity. But this the data returns back to a class type. My question , if result is null what can I sent person who will this method
public AnketorDTO AnketorBul(string tc, string pass)
{
_entity = new AnketDBEntities();
var result = (from i in _entity.Anketors
where i.TC == tc
where i.Sifre == pass
select i).ToList();
if (!result.Any())
-->>> return new AnketorDTO();
Anketor anketor = result.First();
return Converter.ConvertAnketorToAnketorDTO(anketor);
}
with this methot I SENT it by creating a new class type but part which use this methot does not work because the values become null. how can we prevent it.
Client :
AnketorDTO anketor = await client.AnketorBulAsync(txtKullanici.Text, txtSifre.Password);
**if (anketor != null)
lblError.Text = anketor.Adi;**
else
lblError.Text = "Hata";
Can you try this method to see, if it works?
_entity = new AnketDBEntities();
var result = _entity.Anketors.FirstOrDefault(yourexpressions);

Using common methods

i'm using the following method for all data inserting and updating
processes in my application.i just need to pass array of sql quires to
the method.are there any disadvantages of using one common method.does
it cause any performance reduction in the application
public int ExecuteCommand(string[] sqls)
{
numberOfRecordsAffected = 0;
IngresConnection ingresConnection = new IngresConnection(ConnStr);
IngresTransaction ingresTransaction = null;
try
{
ingresConnection.Open();
ingresTransaction = ingresConnection.BeginTransaction();
foreach (string sql in sqls)
{
IngresCommand ingresCommand = new IngresCommand(sql, ingresConnection, ingresTransaction);
ingresCommand.CommandTimeout = 0;
numberOfRecordsAffected += ingresCommand.ExecuteNonQuery();
}
ingresTransaction.Commit();
}
catch
{
if (ingresTransaction != null)
ingresTransaction.Rollback();
ingresConnection.Close();
throw;
}
finally
{
if (ingresConnection != null)
ingresConnection.Close();
}
return numberOfRecordsAffected;
}
See this opinionated article about dynamic sql. You ask specifically about performance which indeed is hurt a lot because your queries can't be cached by the database and each of them need to be parsed. The real worry should be about security though. It's so easy to do it wrong/incomplete at one point or the other and it's even harder to test if it has been messed up somewhere or not.