SSRS 2008 NULL Parameters - reporting-services

How do you pass in null parameters into a SQL 2008 Report? The code that interfaces with the ReportExecution & ReportService2005 web services always yields an error upon executing the ReportExecutionService.Render() method, after I set the parameters (not including the nullable one) via invoking the ReportExecutionService.SetExecutionParameters() method:
"...This report requires a default or user-defined value for the report parameter...to run or subscribe to this report, you must provide a parameter value."
even though that parameter is defined in the .rdl file as being nullable, and defaulting to null.
Must I change my code? Change parameter options in the .rdl file?
var rs = new ReportExecutionService();
rs.Url= "http://Z/ReportServer/ReportExecution2005.asmx";
rs.Credentials = CredentialCache.DefaultCredentials;
rs.ExecutionHeaderValue = new ExecutionHeader();
var executionInfo = rs.LoadReport(ReportTarget, null);
var parameterList = new List<ParameterValue>();
foreach (ParameterValue parameter in Parameters)
{
parameterList.Add(parameter);
}
foreach (var expectedParameter in executionInfo.Parameters)
{
if
(
expectedParameter.Nullable &&
!parameterList.Exists(delegate(ParameterValue pv)
{ return pv.Name == expectedParameter.Name; })
)
{
var parameter = new ParameterValue();
parameter.Name = expectedParameter.Name;
parameter.Value = null;
parameterList.Add(parameter);
}
}
rs.SetExecutionParameters(parameterList.ToArray(), "en-us");
Warning[] warnings = null;
string[] streamIDs = null;
string encoding = null;
string extension = null;
string mime = null;
var content = rs.Render("PDF", null, out extension, out mime, out encoding, out warnings, out streamIDs);

Seems like a bug in SSRS. Especially since I have some reports where the default null value works, and some giving this error message "...report requires a default or user-defined value for the report parameter..."
Anyway, this code seems to work for me in VB.
params = New ArrayList
...
Dim ssrsPrm As New Microsoft.Reporting.WebForms.ReportParameter(param.Name)
ssrsPrm.Values.Add(Nothing)
params.Add(ssrsPrm)
...
Me.ReportViewer1.ServerReport.SetParameters(DirectCast(params.ToArray(GetType(Microsoft.Reporting.WebForms.ReportParameter)), Microsoft.Reporting.WebForms.ReportParameter()))

Does this answer from a slightly different question help? If not, perhaps more code would be helpful.
HTH

Related

Cannot Create a Group, Invalid Scope

I am trying to create a group with the following dot.net code:
var groupDef = new Group()
{
DisplayName = name,
MailNickname = name + " " + GetTimestamp(),
Description = "Group/Team created for testing purposes",
Visibility = "Private",
GroupTypes = new string[] { "Unified" }, // same for all teams
MailEnabled = true, // same for all teams
SecurityEnabled = false, // same for all teams
AdditionalData = new Dictionary<string, object>()
{
["owners#odata.bind"] = owners.Select(o => $"{graphV1Endpoint}/users/{o.Id}").ToArray(),
["members#odata.bind"] = members.Select(o => $"{graphV1Endpoint}/users/{o.Id}").ToArray(),
}
};
// Create the modern group for the team
Group group = await graph.Groups.Request().AddAsync(groupDef);
I am getting a "Method not allowed." error thrown on the last line shown (Group group = await ...).
The scope parameter for the auth provider contains "Group.Read.All Group.ReadWrite.All".
If I add Group.Create to the scope I get an error stating the scope is invalid. Reducing the scope to just "Group.Create" also gives an error.
It certainly appears that I cannot create a group without Group.Create in the scope, but that throws an error at sign in.
Microsoft.Graph is version 3.19.0
Microsoft.Graph.Core is version 1.22.0
I ended up serializing the object and making the Http call with my own code. Basically, something like this:
string json = JsonConvert.SerializeObject(groupDef, jsonSettings);
Group group = HttpPost<Group>("/groups", json);
No permissions were changed.

How to call stored procedure in Entity Framework Core with input and output parameters using mysql

I am using ASP.net Core 2.2 with Entity Framework core 2.2.6 and Pomelo.EntityFrameworkCore.MySql 2.2.0 for connectivity with MySQL, I have a stored procedure which takes 3 input parameters and 1 output parameter. I am able to call it in MySQL workbench like
CALL GetTechniciansByTrade('Automobile', 1, 10, #total);
select #total;
Now I want to call this using entity framework core, the code I am currently using is
var outputParameter = new MySqlParameter("#PageCount", MySqlDbType.Int32);
outputParameter.Direction = System.Data.ParameterDirection.Output;
var results = await _context.GetTechnicians.FromSql("Call GetTechniciansByTrade(#MyTrade, #PageIndex, #PageSize, #PageCount OUT)",
new MySqlParameter("#MyTrade", Trade),
new MySqlParameter("#PageIndex", PageIndex),
new MySqlParameter("#PageSize", PageSize),
outputParameter).ToListAsync();
int PageCount = (int)outputParameter.Value;
Exception I am getting currently is
Only ParameterDirection.Input is supported when CommandType is Text (parameter name: #PageCount)
Can you try below things.
Use exec instead of call
var results = await _context.GetTechnicians.FromSql("EXEC GetTechniciansByTrade(#MyTrade, #PageIndex, #PageSize, #PageCount OUTPUT)"
Select PageCount in stored procedure
I got information from this github issue.
I found the solution using #matt-g suggestion based on this Question.
I had to use ADO.net for this as
var technicians = new List<TechnicianModel>();
using (MySqlConnection lconn = new MySqlConnection(_context.Database.GetDbConnection().ConnectionString))
{
lconn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = lconn;
cmd.CommandText = "GetTechniciansByTrade"; // The name of the Stored Proc
cmd.CommandType = CommandType.StoredProcedure; // It is a Stored Proc
cmd.Parameters.AddWithValue("#Trade", Trade);
cmd.Parameters.AddWithValue("#PageIndex", PageIndex);
cmd.Parameters.AddWithValue("#PageSize", PageSize);
cmd.Parameters.AddWithValue("#PageCount", MySqlDbType.Int32);
cmd.Parameters["#PageCount"].Direction = ParameterDirection.Output; // from System.Data
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
technicians.Add(new TechnicianModel()
{
City = reader["City"].ToString(),
ExperienceYears = reader["ExperienceYears"] != null ? Convert.ToInt32(reader["ExperienceYears"]) : 0,
Id = Guid.Parse(reader["Id"].ToString()),
Name = reader["Name"].ToString(),
Qualification = reader["Qualification"].ToString(),
Town = reader["Town"].ToString()
});
}
}
Object obj = cmd.Parameters["#PageCount"].Value;
var lParam = (Int32)obj; // more useful datatype
}
}

How to return the Json value using WCF WebApi

I have create a one sample WCF rest template WebApi in this i have use Entity Framework to getting the data when i run the service for it return the string value it showing the result but at end of the json value add XML code like below how can i solve this.
[{"AccountId":1,
"AccountNumber":"AC001",
"AccountType":"Restaurant",
"BusinessName"‌​:"Red SpiceInc",
"PrimaryContactFirstName":"Varma",
"PrimaryContactLastName":"Bhupatiraju",
"P‌​rimaryContactPhone":"(949) 374 2114",
"PrimaryContactEmail":"redspice#mybusinessapp.com",
"AccountGuid":"918D3E66-CEFE-11E0-8C2F-0C0B4824019B",
"EntityState":1,"EntityKey":null}]
<?xml version="1.0" encoding="utf-8"?><Stream p1:nil="true" xmlns:p1="w3.org/2001/XMLSchema-instance"; />
My code
[WebGet(UriTemplate = "GetSetting({LocationGuid},{settingName})", ResponseFormat = WebMessageFormat.Json)]
public Stream GetSetting(string LocationGuid, string settingName)
{
string str = string.Empty;
string strJSON = string.Empty;
dynamic contactResponse = new JsonObject();
List<setting> Result;
Result = new List<setting>();
var Location = from acc in objEntity.locations where acc.LocationGuid == LocationGuid select acc;
if (Location.Count() > 0)
{
var LocationId = (from acc in objEntity.locations where acc.LocationGuid == LocationGuid select acc).First();
var objSetting = from cat in objEntity.settings where cat.SettingName == settingName & cat.LocationId == LocationId.LocationId select cat;
setting SettingList = new setting();
foreach (setting setting in objSetting)
{
setting Settinglist = new setting();
Settinglist.SettingId = setting.SettingId;
Settinglist.AccountId = setting.AccountId;
Settinglist.LocationId = setting.LocationId;
Settinglist.SettingName = setting.SettingName;
Settinglist.SettingValue = setting.SettingValue;
Settinglist.FieldType = setting.FieldType;
Result.Add(Settinglist);
}
JavaScriptSerializer js = new JavaScriptSerializer();
strJSON = js.Serialize(Result);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(strJSON));
}
else
{
return null;
}
}
Please help me solve this problem.
I believe return the POCO is enough
the method signature is
public List<setting> GetSetting(string, string)
WCF Web API will serialize the object into json or xml for you as per your request header (accept: application/json, or application/xml)
As was mentioned in misaxi's response, the WebApi WebGet operations generally do not need to concern themselves with how the response is returned. The responsibility of the web operation is to simply return the data. E.g....
[WebGet(UriTemplate = "GetSetting({LocationGuid},{settingName})"]
public List<setting> GetSetting(string LocationGuid, string settingName)
{
List<setting> Result = null;
var Location = from acc in objEntity.locations where acc.LocationGuid == LocationGuid select acc;
if (Location.Count() > 0)
{
Result = new List<setting>();
....
foreach (setting setting in objSetting)
{
....
Result.Add(Settinglist);
}
}
return Result;
}
The fact that the client receives XML, JSON, JSONP, HTML, etc is up to the client (in conjunction with server-side support). The client's request header will include something that looks like Accept: application/json or Accept: application/xml or whatever representation that the client is after. WebApi comes pre-loaded with a few standard formats, XML (the default) and Json. You can introduce more formats as needed to accept a more diverse set of Accept: .... headers, but the conversion from your data to these requested formats are generally out-of-scope for your web operation and rely on the formatters you set up (or were set up by default) when your service is initialized.
Likewise, WebPost operations generally do not care if the body of the request was XML or JSON, by the time the operation is invoked, formatters have already translated that payload into your method's parameters.

not able to call methods after decoding from json

I have a Lua class like below. I am using json to serialize the object and put it in a key value store. I am able to serialize the object and put it in the key value store successfully but i am not able to call any methods of the object after i retrieve the object from the key value store. I understand the json module skips the methods while encoding and my object does not have methods after decoding.
Is there a way to append methods to the class after i decode the object from json to lua ? some thing similar to function pointers in C language.
local class_name = "user_object";
user_object = {}; --user class
function user_object.new (mobile, password, uid)
local self = {};
self.mobile = mobile;
self.uid = uid; -- generate a uid which is a running number.
self.password = password;
self.messages_sent = 0;
self.put_request_count = 0;
self.get_request_count = 0;
self.last_time_active = "";
self.get_tickets = {};
self.put_tickets = {};
self.group_message_stream = {};
self.group_ownerships = {}; -- group names which he is owner of
self.group_memberships = {}; -- group names which he is member of
self.sent_poke_count = 0;
self.sent_poke_stream = {};
self.recv_poke_count = 0;
self.recv_poke_stream = {};
function self:add_put_ticket(ticketid)
table.insert(self.put_tickets, ticketid);
self:incr_put_count();
self:save();
return;
end
function self:add_get_ticket(ticketid)
table.insert(self.get_tickets, ticketid);
self:incr_get_count();
self:save();
return;
end
Function in Lua are first class objects, you can store a function in any variable. The line
function self:add_put_ticket(ticketid)
is equivalent to
self.add_put_ticket = function (self, ticketid)
From there, it should be obvious what to do: define your desired methods where they are accessible and assign them to the appropriate fields after deserialization
You can do this with metatables.
user = { name = 'ponzao' } -- Just a table with values.
User = {} -- Table containing the functions.
function User:allCapsName() return self.name:upper() end -- A method.
setmetatable(user, {__index = User}) -- For unavailable keys all calls are dispatched to User.
print(user:allCapsName()) --> "PONZAO"

Convert SqlCommand Output to List<MyType>?

I am using an ADO.NET SqlCommand with a single SqlDbType.Structured parameter to send a table-valued parameter to a sproc. The sproc returns many rows, which I need to get into a strongly-Typed List of . What is the best way to convert the result set (whether DataTable from a DataAdapter or DataReader bits) into List?
Thanks.
You can use LINQ with a DataReader:
var list = reader.Cast<IDataRecord>()
.Select(dr => new YourType { Name = dr.GetString(0), ... })
.ToList();
The most efficient way is using datareader:
var items = new LinkedList<MyClass>();
using(var connection = GetConnection()) {
using(var cmd = connection.CreateCommand()){
cmd.CommandText = "... your SQL statement ...";
// ... add parameters
cnn.Open();
using(var reader = cmd.ExecuteReader()) {
// accessing values via number index is most efficient
//gets index of column with name "PrimaryKey"
var ndxPrimaryKey = reader.GetOrdinal("PrimaryKey");
var ndxColumn1 = reader.GetOrdinal("Column1");
var ndxColumn2 = reader.GetOrdinal("Column2");
while(reader.Read()) {
var item = new MyClass();
// returns value of column "PrimaryKey" typed to nullable Guid
item.PrimaryKey = reader.GetValue(ndxPrimaryKey) as Guid?;
item.Column1 = reader.GetValue(ndxColumn1) as string;
item.Column2 = reader.GetValue(ndxColumn2) as int?;
items.AddLast(item);
}
}
cnn.Close();
}
}
return items;
i think you can use Dapper to convert a query to a class.
for more information see my answer in this link