How to change the result from web service into pure JSON variable? - arrays

I've .NET web service using C#, and I post the result from this web service in JSON Array variable, but there is something strange with my result its not pure JSON variable. How to change it into pure JSON variable?
here is my code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ModelReport.Report[] GetReports()
{
List<ModelReport.Report> reports = new List<ModelReport.Report>();
string connectionString = ConfigurationManager.ConnectionStrings["ConnWf"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = "select type, sum(OrderQty) as total from tbl_weeklyflash_ID where type <> 'NULL' group by type";
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
command.CommandText = sql;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
ModelReport.Report report = new ModelReport.Report();
report.type = reader["type"].ToString();
report.total = reader["total"].ToString();
reports.Add(report);
}
}
}
return reports.ToArray();
}
here is my current web service result:
-<string>[{"total":"209480","type":"ESL500ML"},{"total":"10177","type":"CHEESE1K"},{"total":"2719928","type":"ESL"},{"total":"145920","type":"WHP"},{"total":"417236.136","type":"UHT"}]</string>
and I want to change it into:
{"report":[{"total":"209480","type":"ESL500ML"},{"total":"10177","type":"CHEESE1K"},{"total":"2719928","type":"ESL"},{"total":"145920","type":"WHP"},{"total":"417236.136","type":"UHT"}]}

Try building a WCF service. Refer Making of JSON Webservice using C#.NET.
You can learn to create WCF services using this.
Hope it helps.

Related

How can you run a report from the ReportServer database without building subscriptions?

I'd like to build a back end system that allows me to run each report every night and then query the execution log to see if anything failed. I know you can build out subscriptions for these reports and define parameters etc but is there a way to execute each report from the ReportServer database using TSQL without building out each subscription?
I understand that your overall goal is that you want to automate this and not have to write a subscription for every report. You say you want to do it in T-SQL, but is that required to meet your overall goal?
If you can accept, say .Net, then you can use the System.Data.SqlClient.SqlConnection and related classes to query your report server catalog and fetch a listing of all your reports.
Then you can use System.Net.WebClient or similar tool to attempt to download a pdf of your report. From there you can either read your execution log, or catch the error in the .Net Code.
EDIT
Well, since you accepted the answer, and it seems you may go this route, I'll mention that if you're not familiar with .net, it may be a long path for you. Here's a few things to get you started.
Below is a c# function utilizing .Net that will query the report catalog. If safeImmediate is set to true, it will only capture reports that can be run immediately, as in there are no parameters or the defaults cover the parameters.
IEnumerable<string> GetReportPaths(
string conStr,
bool safeImmediate // as in, you can exexute the report right away without paramters
) {
using (var con = new SqlConnection(conStr))
using (var cmd = new SqlCommand()) {
cmd.Connection = con;
cmd.CommandText = #"select path from catalog where type=2";
con.Open();
if (safeImmediate)
cmd.CommandText = #"
select path
from catalog
cross apply (select
params = convert(xml, Parameter).value('count(Parameters/Parameter)', 'int'),
defaults = convert(xml, Parameter).value('count(Parameters/Parameter/DefaultValues/Value)', 'int')
) counts
where type = 2
and params = defaults
and path not like '%subreport%' -- this is not standard. Just works for my conventions
";
using (var rdr = cmd.ExecuteReader())
while (rdr.Read())
yield return rdr["path"].ToString();
}
}
The next function will download a report given proper paths passed to it:
byte[] DownloadReport (
WebClient wc,
string coreUrl,
string fullReportPath,
string parameters = "" // you won't use this but may come in handy for other uses
) {
var pathToViewer = "ReportServer/Pages/ReportViewer.aspx"; // for typical ssrs installs
var renderOptions = "&rs:Format=pdf&rs:Command=Render"; // return as pdf
var url = $#"{coreUrl}/{pathToViewer}?{fullReportPath}{parameters}{renderOptions}";
url = Uri.EscapeUriString(url); // url's don't like certain characters, fix it
return wc.DownloadData(url);
}
And this utilizes the functions above to find what's succeeding and whats not:
var sqlCon = "Server=yourReportServer; Database=ReportServer; Integrated Security=yes"; // or whatever
var ssrsSite = "http://www.yourSite.org";
using (var wc = new WebClient()) {
wc.UseDefaultCredentials = true; // or whatever
int loops = 3; // get rid of this when you're ready for prime-time
foreach(var path in GetReportPaths(sqlCon, true)) {
try {
DownloadReport(wc, ssrsSite, path);
Debug.WriteLine($"Success with: {path}");
}
catch(Exception ex) { // you might want to get more specific
Debug.WriteLine($"Failed with: {path}");
}
if (loops-- == 0)
break;
}
}
Lots to learn, but it can be very beneficial. Good luck.

Reading from CosmosDB and write to Azure SQL

I have an Azure function to read from Cosmos DB and write to SQL. Since I am new to coding I have a little of struggle to understand how to read the incoming document. I can see that documents are shown at input:
public static async Task Run([CosmosDBTrigger(
databaseName: "ToDoList",
collectionName: "Items",
ConnectionStringSetting = "CosmosDB",
LeaseCollectionName = "leases")]IReadOnlyList<Document> input, ILogger log)
{
if (input != null && input.Count > 0)
{ }
I know that I have to read the document and deserialise it to a C# object which I have this code for (assuming it is correct):
Record resultRecord = JsonConvert.DeserializeObject<Record>(jsonString);
I am lost how to get the data from the json document and write it to the C# object. The connecting part is confusing for me.
I also have a SQL code, and again I dont understand how I should connect my C# object so the data can be read and written to SQL database.
var cnnString = "sqlConnection"; // Connecting to Azure SQL Database
using (var sqlConnection = new SqlConnection(cnnString)) // Start up sql connectin with connectionstring
{
sqlConnection.Open();
var cmd = new SqlCommand
{
//Insert into command (used to insert data into a table)
CommandText = #"insert into [dbo].[Player] ([User] values(#User)",
CommandType = CommandType.Text,
Connection = sqlConnection,
};
var record = new Record();
//set parameters
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#User", record.Email));
await cmd.ExecuteNonQueryAsync();
I am not sure if this is the right way of asking a question about a code, but I appreciate any help.
You want to get data from a json document,we can use the Newtonsoft.Json.dll file to parse the json document.
I think you can change you code like this:
List<Info> jobInfoList = JsonConvert.DeserializeObject<List<Info>>(json);
And here is a sample about how to get data from a json documnet:
class Program
{
static void Main(string[] args)
{
string json = #"[{'id':9527,'username':'admin'}]";
List<Info> jobInfoList = JsonConvert.DeserializeObject<List<Info>>(json);
foreach (Info jobInfo in jobInfoList)
{
Console.WriteLine("UserName:" + jobInfo.username);
}
}
}
public class Info
{
public string id { get; set; }
public string username { get; set; }
}
You can declare variables to receive the data which you want to get from the json String in foreach . Then you can insert these data into your sql database as the parameters.
How to connect to the sql database and write data to sql database,you can see:
Quickstart:
Use .NET (C#) with Visual Studio to connect and query an Azure SQL database
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-dotnet-visual-studio#insert-code-to-query-sql-database

Export CSV file to FTP site using SQL

Does anyone know how to export CSV file to FTP site in SQL management studio?
I am currently using
exec xp_cmdshell 'net use \ftp://213.32.32 \user:fjdowj ddfdf'
But it doesn't work at all
Thanks
you can try CLR stored procedure to generate CSV file and export to FTP site.
Generating CSV file to a path is given below:
public static void GenerateCSVFile(SqlString queryToGetData, SqlString folderPath)
{
string sqlCommand;
string filePath;
try
{
sqlCommand = queryToGetData.ToString();
filePath = folderPath.ToString() + "\\GeneratedFile" + ".csv";
using (SqlConnection connection = new SqlConnection(
"context connection=true"))
{
connection.Open();
SqlCommand command = new SqlCommand(sqlCommand,connection);
using (SqlDataReader reader = command.ExecuteReader())
{
DataTable table = new DataTable();
table.Load(reader);
StringBuilder builder = new StringBuilder();
List<string> columnNames = new List<string>();
List<string> rows = new List<string>();
foreach (DataColumn column in table.Columns)
{
columnNames.Add(column.ColumnName);
}
builder.Append(string.Join(",", columnNames.ToArray())).Append("\n");
foreach (DataRow row in table.Rows)
{
List<string> currentRow = new List<string>();
foreach (DataColumn column in table.Columns)
{
object item = row[column];
currentRow.Add(item.ToString());
}
rows.Add(string.Join(",", currentRow.ToArray()));
}
builder.Append(string.Join("\n", rows.ToArray()));
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.Write(builder.ToString());
}
}
}
}
catch(Exception ex)
{
throw;
}
}
Once you generate file, you can use the below approach to load to FTP path.
FTP Directly in SQL
xp_cmdshell is disabled by default (for very good reasons) on all recent versions of SQL Server. You could re-enable it manually (and I encourage you NOT to), but then you'd need an ftp command line tool to do the upload-- I don't think that net use command is going to do the trick. If you did manage to map an ftp end point as a drive with net use as the SQL Server service user, you would still need to achieve copying the file from SSMS to the filesystem on the server before running the FTP job.

Missing assembly reference for SqlConnection

I'm still new to MVC and dapper ORM.
Suppose I use dapper for MVC and and when I try to build solution, it showing message:
'SqlConnection does not contain a definition for'Query' and no extension method 'Query' accepting a first argument of type 'SqlConnection'.
here is the code:
using System.Collections.Generic;
using System.Data.SqlClient;
public string Connectionstring = #"Data Source = KL - PT - 049\sqlexpress;Initial Catalog = Record; Integrated Security = True";
public IEnumerable<Customer> GetCustomers()
{
using (SqlConnection conn = new SqlConnection(Connectionstring))
{
conn.Open();
var customer = conn.**Query**<Customer>("Select * from Customer");
return customer;
}
my question is: does the Query above should be fine if I use that way? since I already use data.sqlClient reference?
Add
using Dapper;
at the top of the file.
Note: in recent versions of Visual Studio you can also just press ctrl+. on the unresolved extension method and it will offer to fix it for you:

Can we connect Sharepoint to SQL Server 6.5?

Not able to import application definition file!! Error: The metadata object with Name 'XYZ' and of Type 'LobSystemInstance' has a Property with Name 'DatabaseAccessProvider' that has either an invalid value or Type. Error was encountered at or just before Line: '10' and Position: '10'.
line 10 in ADF:
<"Property Name="DatabaseAccessProvider" Type="System.String">SqlOledb<"/Property>
Please give me ideas on how to display data from SQL Server 6.5 in Sharepoint?
The value of the node is invalid. You need to use SqlServer or OleDb. Check out this page for more information:
http://msdn.microsoft.com/en-us/library/ms550725(office.12).aspx
Im just starting on a similar task (so I found your unanswered question). I am trying to copy our documentation library in Sharepoint to an SQL db. Its not opening your file directly from SQL its using some c# code to setup a job which opens the sharepoint which may be what you are wanting.
There are two methods I have found so far:
One is to copy your data from sharepoint to a linked list in Access and then use the OLEDB methods in to open it.
Found here: C# Sync MS Access database to sql server
private static void BulkCopyAccessToSQLServer
(CommandType commandType, string sql, string destinationTable)
{
string connectionString = #"C:\Migration\Sharepoint Access SQL Batch Job\Database11.accdb";
using (DataTable dt = new DataTable())
{
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Migration\Sharepoint Access SQL Batch Job\Database11.accdb;Jet OLEDB:Database Password=password";
//using (OleDbConnection conn = new OleDbConnection(Settings.Default.CurriculumConnectionString))
using (OleDbConnection conn = new OleDbConnection(ConnStr))
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
cmd.CommandType = commandType;
cmd.Connection.Open();
adapter.SelectCommand.CommandTimeout = 240;
adapter.Fill(dt);
adapter.Dispose();
}
using (SqlConnection conn2 = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))
using (SqlConnection conn2 = new SqlConnection(connectionString))
{
conn2.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(conn2))
{
copy.DestinationTableName = destinationTable;
copy.BatchSize = 1000;
copy.BulkCopyTimeout = 240;
copy.WriteToServer(dt);
copy.NotifyAfter = 1000;
}
}
}
}
The other is to use the Microsoft.Sharepoint libraries and open your sharepoint directly from the c# then copy it into your SQL.
Found here: http://www.dotnetspark.com/kb/3573-fetching-lists-from-sharepoint-2010-site.aspx
using (SharePointclientObj.ClientContext ctx = new SharePointclientObj.ClientContext(clientContext))
{
//Get the site
SharePointclientObj.Web site = ctx.Web;
ctx.Load(site);
//Get Lists
ctx.Load(site.Lists);
//Query
ctx.ExecuteQuery();
//Fill List
foreach (SharePointclientObj.List list in site.Lists)
{
Console.WriteLine(list.Title);
}
}

Resources