why doesnt' it use the parameter in this raw sql? - entity-framework

I am using this code:
SqlParameter pNombreUsuario = new SqlParameter("NombreUsuario", paramNombreUsuario);
object[] parametros = new object[] { pNombreUsuario };
string passwordDB = dbContext.Database.SqlQuery<string>("select password from Personal where NombreUsuario = #NombreUsuario", parametros)
.SingleOrDefault<string>();
but the query that is sent to the database is:
select password from Personal where NombreUsuario = #NombreUsuario
Why the parameter with the username name is not used?
Thanks.

The docs indicate that you should send an array of object values rather than SqlParameter objects.
E.g.
string passwordDB = dbContext.Database
.SqlQuery<string>("select password from Personal where NombreUsuario = #p0", paramNombreUsuario)
.SingleOrDefault<string>();
Does that work for you?
Edit: I misread the docs. Try this:
string passwordDB = dbContext.Database
.SqlQuery<string>(
"select password from Personal where NombreUsuario = #NombreUsuario",
new SqlParameter("NombreUsuario", paramNombreUsuario))
.SingleOrDefault<string>();

Related

How do I Show a SPList item Name in an Email sent by a timerJob?

I need to send an Email with a list items name of the rows my caml query picks out. I have this code:
SPQuery filter = new SPQuery();
filter.Query = string.Format("<Where><Leq><FieldRef Name=\"Revisionsdatum\" /><Value Type=\"DateTime\">{0}</Value></Leq></Where>", DateTime.Today.AddDays(14).ToString("yyyy-MM-ddThh:mm:ssZ"));
SPListItemCollection items = yourList.GetItems(filter);
foreach (var i in items)
{
string from = string.Empty;
string smtpAddress = string.Empty;
string to = "Someone#someCompany.com";
string subject = "Dudate is coming";
string body = "<h1>Hello!</h1><p>In to weeks an importent dudates comes({0}) with the name {2}.";//Here I would like to ad the dudate and the ListItems Name but how?
// get a reference to the current site collection's content database
SPWebApplication webApplication = this.Parent as SPWebApplication;
SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];
// get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database
SPWeb rootWeb = contentDb.Sites[0].RootWeb;
SPList listjob = rootWeb.Lists.TryGetList("Tasks");
// Get sender address from web application settings
from = rootWeb.Site.WebApplication.OutboundMailSenderAddress;
// Get SMTP address from web application settings
smtpAddress = rootWeb.Site.WebApplication.OutboundMailServiceInstance.Server.Address;
// Send an email if the news is approved
bool emailSent = SendMail(smtpAddress, subject, body, true, from, to, null, null);
}
I would bee greatfull for your answer!
You can get it as follows:
foreach (SPListItem item in items) \\ items is your SPListItemCollection
{
var fieldValue = item["Field Name"].ToString();
}
To convert DateTime object to CAML query use SPUtility.CreateISO8601DateTimeFromSystemDateTime() method.
Fields you need are referenced by i["Title"] and i["DueDate"].
Use StringBuilder object in foreach loop to construct the body of your mail and send the email after the loop. Your code will send one mail for each task.

IPP v3 Invoice QueryService not working with Skip/Take when using non-default fields

I'm trying to query invoices using the .NET IPP DevKit v3.
Following all the directions found on the documentation site, I can query invoices and add skip/take/order by/where/etc to the query when using ONLY default fields. But, as soon as I add non-default fields, skip/take/order by/where/etc does NOT seem to work.
Here's the error:
System.ArgumentException was unhandled
HResult=-2147024809
Message=Expression of type 'System.Collections.Generic.IEnumerable`1[<>f__AnonymousType0`3[Intuit.Ipp.Data.Invoice,Intuit.Ipp.Data.Line[],Intuit.Ipp.Data.LinkedTxn[]]]' cannot be used for parameter of type 'System.Linq.IQueryable`1[<>f__AnonymousType0`3[Intuit.Ipp.Data.Invoice,Intuit.Ipp.Data.Line[],Intuit.Ipp.Data.LinkedTxn[]]]' of method 'System.Linq.IQueryable`1[<>f__AnonymousType0`3[Intuit.Ipp.Data.Invoice,Intuit.Ipp.Data.Line[],Intuit.Ipp.Data.LinkedTxn[]]] Skip[<>f__AnonymousType0`3](System.Linq.IQueryable`1[<>f__AnonymousType0`3[Intuit.Ipp.Data.Invoice,Intuit.Ipp.Data.Line[],Intuit.Ipp.Data.LinkedTxn[]]], Int32)'
Source=System.Core
What am I missing here?
Code:
string AppToken = "your AppToken goes here";
string AppConsumerKey = "your AppConsumerKey goes here";
string AppConsumerKeySecret = "your AppConsumerKeySecret goes here";
string AccessToken = "your AccessToken goes here";
string AccessTokenSecret = "your AccessTokenSecret goes here";
string RealmCompanyId = "your RealmId goes here";
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(AccessToken, AccessTokenSecret, AppConsumerKey, AppConsumerKeySecret);
ServiceContext context = new ServiceContext(AppToken, RealmCompanyId, IntuitServicesType.QBD, oauthValidator);
QueryService<Intuit.Ipp.Data.Invoice> qs = new QueryService<Intuit.Ipp.Data.Invoice>(context);
// This works...
var defaultQuery = qs.Select(c => c).Skip(0).Take(10).OrderBy(c => c.Id);
var defaultList = defaultQuery.ToList();
// This works...
var nonDefaultQuery = qs.Select(c => new { c, c.Line, c.LinkedTxn });
var nonDefaultList = nonDefaultQuery.ToList();
// This does NOT work!!
var nonDefaultQueryWithSkip = qs.Select(c => new { c, c.Line, c.LinkedTxn }).Skip(0).Take(10);
var nonDefaultListWithSkip = nonDefaultQueryWithSkip.ToList();
I tried on the API explorer-
Select *,Line.*, LinkedTxn.* FROM Invoice startPosition 1 maxResults 10 (which is your last query) and it works fine but not from .net sdk. I will double check this on the .net SDK and get back to you. Can you verify that you get the correct results on API explorer from this query?
This now works in the latest version (IppDotNetSdkForQuickBooksApiV3.2.0.0)
Here's an example:
QueryService<Intuit.Ipp.Data.Invoice> qs = new QueryService<Intuit.Ipp.Data.Invoice>(context);
string query = string.Format("SELECT *, Line.* FROM Invoice ORDERBY Id STARTPOSITION {0} MAXRESULTS {1}", startPos, pageSize);
var recs = qs.ExecuteIdsQuery(query);
foreach (Intuit.Ipp.Data.Invoice rec in recs)
{
// do stuff...
}
.

execute stored proc in ExecuteStoreQuery EF. is this a bug in EF?

trying to execute the stored proc in EF using the following code:
var params = new object[] {new SqlParameter("#FirstName", "Bob")};
return this._repositoryContext.ObjectContext.ExecuteStoreQuery<ResultType>("GetByName", params);
but keep getting this error:
Procedure or function 'GetByName' expects parameter '#FirstName',
which was not supplied.
and from sql profiler:
exec sp_executesql N'GetByName',N'#FirstName nvarchar(100),#FirstName=N'Bob'
what is wrong wit the above ExecuteStoreQuery code?
Ignoring the fact that params is a reserved word...
Think your query needs to be:
var params = new object[] {new SqlParameter("#FirstName", "Bob")};
return this._repositoryContext.ObjectContext.ExecuteStoreQuery<ResultType>("exec GetByName #FirstName", params);
Should also say that if that proc is a standard part of your database and data model then you should import it into your EDM so it's available directly on your context.
Use the ExecuteFunction instead of ExecuteStoreQuery which is more suitable for the "ad-hoc" queries.
var parameters = new ObjectParameter[] {new ObjectParameter("FirstName", "Bob")};
return this._repositoryContext.ObjectContext.ExecuteFunction<ResultType>("GetByName", parameters);
The stored procedures can also be mapped as function in the context and thus can be used as typed method. Take a look at Using stored procedures with Entity Framework.
This is what I did to use a SP in EF, if you have multiple parameters:-
public virtual ObjectResult<GetEpisodeCountByPracticeId_Result> GetEpisodeCountByPracticeId(Nullable<int> practiceId, Nullable<System.DateTime> dat1)
{
SqlParameter practiceIdParameter = practiceId.HasValue ?
new SqlParameter() { ParameterName = "practiceId", Value = practiceId, SqlDbType = SqlDbType.Int } :
new SqlParameter() { ParameterName = "practiceId", SqlDbType = SqlDbType.Int };
SqlParameter dat1Parameter = dat1.HasValue ?
new SqlParameter() { ParameterName = "dat1", Value = dat1, SqlDbType = SqlDbType.DateTime }:
new SqlParameter() { ParameterName = "dat1", SqlDbType = SqlDbType.DateTime };
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<GetEpisodeCountByPracticeId_Result>("exec GetEpisodeCountByPracticeId #practiceId, #dat1", practiceIdParameter, dat1Parameter);
}
If you dont add the parameters (e.g. #practiceId) in the commandText property then you get the error you received

Cannot set privacy while creating a Facebook Album

I cannot set the privacy while creating a new Album in fb using facebook-c#-sdk 5.0.25
var albumDetails = new Dictionary<string, object>();
albumDetails.Add("name", "test name");
albumDetails.Add("description", "test description");
albumDetails.Add("privacy", "ALL_FRIENDS"); // I get an error here,
//Invalid Privacy value
var fbResult = fb.Post("me/albums", albumDetails);
I tried setting to other values like "EVERYONE" but without success. Please let me know what is the correct set of values.
Thanks,
Partha
According to this page, it should be a json encoded value something like (i suppose): [value: 'ALL_FRIENDS'] or {value: 'ALL_FRIENDS'}
This works for me :-
dynamic parameters = new ExpandoObject();
parameters.name = theName;
parameters.privacy = "{'value':'" + theValue + "'}";

How to pass default keyword for table valued function call in ADO.NET

So here's the deal. In our database, we wrap most of our reads (i.e. select statements) in table valued functions for purposes of security and modularity. So I've got a TVF which defines one or more optional parameters.
I believe having a TVF with defaulted parameters mandates the use of the keyword default when calling the TVF like so:
select * from fn_SampleTVF(123, DEFAULT, DEFAULT)
That's fine, everything works in the query analyzer, but when it comes time to actually make this request from ADO.NET, I'm not sure how to create a sql parameter that actually puts the word default into the rendered sql.
I have something roughly like this now:
String qry = "select * from fn_SampleTVF(#requiredParam, #optionalParam)";
DbCommand command = this.CreateStoreCommand(qry, CommandType.Text);
SqlParameter someRequiredParam = new SqlParameter("#requiredParam", SqlDbType.Int);
someRequiredParam.Value = 123;
command.Parameters.Add(someRequiredParam);
SqlParameter optionalParam = new SqlParameter("#optionalParam", SqlDbType.Int);
optionalParam.Value = >>>> WTF? <<<<
command.Parameters.Add(optionalParam);
So, anybody got any ideas how to pass default to the TVF?
SqlParameter optionalParam = new SqlParameter("#optionalParam", SqlDbType.Int);
optionalParam.Value = >>>> WTF? <<<<
command.Parameters.Add(optionalParam);
You don't have to add above code (The optional parameter) for default. SQL Server will use the default as defined in your UDF. However if you would like to pass different value then you can pass:
SqlParameter optionalParam = new SqlParameter("#optionalParam", SqlDbType.Int);
optionalParam.Value = newValue;
command.Parameters.Add(optionalParam);
I would have done so:
public void YourMethod(int rparam, int? oparam = null)
{
String qry = string.Format("select * from fn_SampleTVF(#requiredParam, {0})"
, !oparam.HasValue ? "default" : "#optionalParam");
SqlParameter someRequiredParam = new SqlParameter("#requiredParam", SqlDbType.Int);
someRequiredParam.Value = rparam;
command.Parameters.Add(someRequiredParam);
if (oparam.HasValue)
{
SqlParameter optionalParam = new SqlParameter("#optionalParam", SqlDbType.Int);
optionalParam.Value = oparam.Value;
command.Parameters.Add(optionalParam);
}
}
You can pass Null as the parameter value.
This article shows examples: http://support.microsoft.com/kb/321902