Setting connecting string in Blazor Telerik Report Viewer - telerik

I know this should be easier than this, I was reading the Telerik Documentation since hours but without solution.
I have Blazor Server Side project.
I added Telerik Report Viewer.
<ReportViewer ViewerId="rv1"
ServiceUrl="/api/reportdesigner"
ReportSource="#Source"
Parameters="#ParametersOptions"
ScaleMode="#(ScaleMode.Specific)"
Scale="1.0" />
and here is the data that I am binding to from the component
private ReportSourceOptions Source => new()
{
Report = SelectedReport?.Name ?? string.Empty,
Parameters = new Dictionary<string, object>()
{
{ "ConnectionString" , "TelerikConnectionString" }
}
};
private readonly ParametersOptions ParametersOptions = new()
{
Editors = new EditorsOptions
{
MultiSelect = EditorType.ComboBox,
SingleSelect = EditorType.ComboBox,
}
};
The component show in the page, but it complains about the connection string,
which I am struggling to figure out to set
here is the error message
Unable to get report parameters. An error has occurred. Unable to establish a connection to the database. Please verify that your connection string is valid. In case you use a named connection string from the application configuration file, make sure the name is correct and the connection string settings are present in the configuration file of your application.
I added the connection string in the C:\Users\USERNAME\AppData\Roaming\Telerik Reporting\WebReportDesignerSettings.json
{
"ConnectionStrings": [
{
"name": "TelerikConnectionString",
"connectionString": "Server=.\\;Initial Catalog=AdventureWorks;Integrated Security=true",
"providerName": "System.Data.SqlClient"
}
]
}

The json file should be present in your Blazor application. You can have a look at the example Blazor projects that come with your installation, located at (Replace R3 2022 with your release version):
C:\Program Files (x86)\Progress\Telerik Reporting R3 2022\Examples\CSharp\.NET 7\BlazorIntegrationDemo
You can specify your connection string in appsettings.json file
"ConnectionStrings": {
"Telerik.Reporting.Examples.CSharp.Properties.Settings.TelerikConnectionString": {
"connectionString": "Data Source=.\\;Initial Catalog=AdventureWorks;Integrated Security=SSPI",
"providerName": "System.Data.SqlClient"
}
You may need to set its Build Action to Content and Copy if Newer.

Related

Configuration doesn't pick connection string from secrets.json file in ASP NET Core MVC 6.0 lts

I created ASP NET Core MVC 6 lts app with individual user accounts with Visual Studio 2022 preview 6.0. I moved connection string from appsettings.json to secrets.json. I start the app with IIS Express and apply migrations from exception page that opens. It works.
But when I try to apply additional migrations from Package Manager Console I get an error "connectionString can't be null".
Add services to the container. This is from Program.cs:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
This is appsettings.json, connection string value removed:
"ConnectionStrings": {
"DefaultConnection": ""
},
This is Secrets.json:
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=DESKTOP-HIPPIDT;Initial Catalog=KehittajaLocalDb;Integrated Security=True;MultipleActiveResultSets=True"
}
}
In .NET 6,
You do not need to specify AddUserSecrets<>.
As mentioned here ,
WebApplication.CreateBuilder initializes a new instance of the
WebApplicationBuilder class with preconfigured defaults. The
initialized WebApplicationBuilder (builder) provides default
configuration and calls AddUserSecrets when the EnvironmentName is
Development
All you need to do is get the connection string from the builder.Configuration like below:
var dbConnectionString = builder.Configuration["ConnectionStrings:DevelopmentConnection"];
Then, you can specify the connection with AddDbContext<>:
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(dbConnectionString);
});
I added this to the Program.cs, now it works as expected. I don't know how come it worked when migrations were applied from exception page "Apply Migrations" button anyway.
// Add services to the container
if(builder.Enviroment.IsDevelopment())
{
builder.Configuration.AddUserSecrets<Program>();
}
..other code

Open Api 3.0 Swagger application with Visual Studio 19 - database connection problem

I have to make application for .NET5.0. (Core). I have installed packages Devart.Data (5.0.2658) and Devart.Data.Oracle(9.14.1234).
I use 32 bits oracle client in my computer.
I have switched my application to x86 mode.
I need to connect to a Oracle 12 server.
Here is my code:
[Route("GetMyData")]
[HttpGet]
public List<Cis_titul_pred> GetCiselnik()
{
List<DataModule.BO.Cis_titul_pred> testlist =
DataModule.DAL.Cis_titul_predDB.Instance.GetList();
return testlist;
}
public List<Cis_titul_pred> GetList()
{
List<Cis_titul_pred> cis_titul_predList = null;
using (OracleConnection oraConnect = new OracleConnection(AppConfig.ConnectionString))
{
OracleCommand oraCommand = new OracleCommand(selectList, oraConnect);
oraCommand.CommandType = CommandType.Text;
oraConnect.Open();
using (OracleDataReader oraReader = oraCommand.ExecuteReader())
{
if (oraReader.HasRows)
{
cis_titul_predList = new List<Cis_titul_pred>();
while (oraReader.Read())
{
cis_titul_predList.Add(FillCis_titul_pred(oraReader));
}
}
oraReader.Close();
}
oraConnect.Close();
}
return cis_titul_predList;
}
When I created .NET5.0 Desktop (WinForms) application , everything worked properly - I could connect to Oracle server and read data.
When I created .NET5.0 WEB application , everything worked properly - I could connect to Oracle server and read data.
When I created .NET5.0 OpenApi application , I got error message "Devart.Data.Oracle.OracleException (0x80004005): Server did not respond within the specified timeout interval
at Devart.Data.Oracle.dp.a(cj A_0, di A_1)
at Devart.Data.Oracle.OracleInternalConnection..ctor(cj connectionOptions, OracleInternalConnection proxyConnection)
at Devart.Data.Oracle.ci.a(ae A_0, Object A_1, DbConnectionBase A_2) Etc. ... Etc..."
I use the same code to connect to the Oracle server in all three applications
I tried change target framewor to NET.Core 3.0, or NET.Cre 3.1, but without success.
Any ideas?
What can I do?
What do you mean by .NET5.0 OpenApi application? It's the same architecture with .net5 web... Please check If you have a correct and same connection string in your appSettings.json file. Also consider using dependancy injection instead of creating OracleConnection instance inside controllers

display build version on web page

I am developing a web site using asp.net core.
And I publish it with Visual Studio or/and VSTS.
I want to display some information about which build it is on the web page.
(something like rev 2016.9.20.4002)
How can I do that?
You can track it with build number.
Go to your VSTS site and create build definition
Select General tab, specify build number format, for example: $(date:yyyyMMdd)$(rev:.r)
(Optional) Select Triggers tab, check Continuous integration (CI) and configure filters if you want queue build for each check-in.
Configure other settings (e.g. steps/task in Build tab)
After build complete, go to the summary of that build definition (click build definition title hyperlink to go to summary page), the result will be like this:
Steps to display build number to your website:
Install Replace Tokens extension to you VSTS
Edit your build definition to add Replace token task
Specify target files and root directory (for asp.net core app, you can specify **\appsettings.json)
Select Variable tab and add a new variable. Save your build definition
Edit appsettings.json file of your asp.net project. Sample code:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-ab933d83-8f4b-4024-9f3c-1aef5339a8f3;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"CodeVersion": {
"Num": "#{MyBuildNumber}#"
}
}
Add logical to your asp.net project to read appsettings.json to get specific value and display in the page.
Check in your code and queue build.
After a day of research, finally found/created a better option than using any random app (Replace Token) from Marketplace.
The option I am talking is already available in VSTS, Azure CLI task.
Here are the stpes:
Add setting BUILD_NUMBER with initial value of 1.0 in appsettings.json
Read appsettings.json in your app and display it. I am sure you all are smart enough to figure out how to use appsettings to display Build Number on your WebApplication.
In Azure Portal, similarly create an App Setting named BUILD_NUMBER with initial value of 1.0 in Azure Application settings section under App Services for your App.
In VSTS, In your Release definition, add a task Azure CLI.
Populate required fields such as Azure Subscription, Script Location with Inline script and last but most important Inline Script with following CLI command
az webapp config appsettings set -n iCoreTestApi -g ArchitectsSandbox -s Dev --settings BUILD_NUMBER=$(Build.BuildNumber)
Command explanation:
iCoreTestApi should be replaced by your real WebApp or Api name in Azure
ArchitectsSandbox should be replaced by your resource group in Azure
Dev is the slot name, you may or may not have it.
Rest of the command remains same.
Once you will queue new build, after successful completion of the deployment, you can see app settings section on Azure is updated with new BUILD_NUMBER.
Let me know if you still have any question.
Do you mean something like this:
In project.json:
{
"title": "Your Application name",
"version": "2016.9.20.4002",
"copyright": "Your Company 2016",
"description": "Awesome ASP.Net Core Application",
"dependencies": {
//rest of project.json
You can then create a property in your view model or model such as:
public static string Version
{
get
{
var assembly = Assembly.GetExecutingAssembly();
var fileVersion = GetCustomAttribute<AssemblyFileVersionAttribute>(assembly);
return fileVersion?.Version;
}
}
In your view:
#model Namespace.CustomViewModel
<!--Other HTML Code-->
<span id="applicationVersion">#CustomViewModel.Version</span>
Looks like ApplicationEnvironment class is what you need:
var appEnv = new Microsoft.Extensions.PlatformAbstractions.ApplicationEnvironment();
string version = appEnv.ApplicationVersion;
Also
How can I auto-increment an MVC 6 version number? may be also interesting to you, but keep in mind, that IApplicationEnvironment has been removed.
Just as an alternative option, you could read the time that the assembly was created and display it in a version format. Every time the assembly is rebuilt, this value would change to the time it was created.
(adapted from this answer for .Net Core)
public static class AppInfo
{
private static Lazy<string> buildVersion =
new Lazy<string>(() => GetBuildVersion(Assembly.GetEntryAssembly()));
public static string BuildVersion { get; } = buildVersion.Value;
private static string GetBuildVersion(Assembly assembly)
{
var filePath = assembly.Location;
const int c_PeHeaderOffset = 60;
const int c_LinkerTimestampOffset = 8;
var buffer = new byte[2048];
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
stream.Read(buffer, 0, 2048);
var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset);
var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset);
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var linkTimeUtc = epoch.AddSeconds(secondsSince1970);
var localTime = TimeZoneInfo.ConvertTime(linkTimeUtc, TimeZoneInfo.Local);
var minutesFromMidnight = localTime.Minute + localTime.Hour * 60;
return localTime.ToString("yyyy.M.dd.") + minutesFromMidnight;
}
}
Then just reference it in Razor as:
#AppInfo.BuildVersion
It may be not exactly what requested but was quite efficient in my situation. If docker is used to build and deploy web apps, consider adding this step to your CI build script before docker build command (bash):
echo ENV BUILD_NUMBER=$(Build.BuildNumber) >> Dockerfile
In the app code just use BUILD_NUMBER environment variable.
The advantage of this method is that build number value becomes metadata of the docker image just like labels but you can also access it from the inside your app.

TFS 2015 server side plugin deployment (using VS 2013)

I am using Visual Studio 2013 and wrote a TFS 2015 server side plugin. Created a local TFS 2015 environment and checked-in files to test it, I found that it works as expected.
I want to deploy my plugin: Following the instructions on internet I changed my plugin code's output path to : ..............\Program Files\Microsoft Team Foundation Server 14.0\Application Tier\Web Services\bin\Plugins. So, my plugin.dll and plugin.pdb files are in this location.
After this step; I am stuck, I tried to go to Team Explorer -> Settings -> Source Control(under Team Project)-> Check-in Policy -> Add but I wasn't able to find my file.
I need help to deploy my plug-in.
Your server side plugin will not show up in the Check-in Policy Add dialog. It will however execute when the Check In button is hit for every client that connects to the TFS server where the plugin is deployed. Based on the plugin code it will either approve or deny the check-in. In case it denies the check-in you can supply a message for the user about what to fix.
Here is an example that just rejects if the code reviewer is claimed to be GOD. You can also check the comment section and look for required elements if you like.
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.TeamFoundation.Build.Server;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Server;
using System.Collections.Generic;
using Microsoft.TeamFoundation.VersionControl.Server;
namespace TFSPlugin
{
public class FittingSoftwarePlugin : ISubscriber
{
public string Name { get { return this.GetType().Name; } }
public SubscriberPriority Priority { get { return SubscriberPriority.Normal; } }
public Type[] SubscribedTypes() { return new[] { typeof(CheckinNotification) }; }
public EventNotificationStatus ProcessEvent(IVssRequestContext requestContext, NotificationType notificationType, object notificationEventArgs,
out int statusCode, out string statusMessage, out ExceptionPropertyCollection properties)
{
statusCode = 0;
properties = null;
statusMessage = String.Empty;
try
{
var checkinNotificationArgs = notificationEventArgs as CheckinNotification;
if (notificationType == NotificationType.DecisionPoint && checkinNotificationArgs != null)
{
var codeReviewer = checkinNotificationArgs.CheckinNote.Values.FirstOrDefault(v => v.Name.Equals("Code Reviewer"));
if (codeReviewer!=null && codeReviewer.Value.Equals("GOD", StringComparison.InvariantCultureIgnoreCase))
{
statusMessage = "GOD cannot be used as a code reviewer as he is not trustworthy!";
return EventNotificationStatus.ActionDenied;
}
}
}
catch (Exception e)
{
// Log error
}
return EventNotificationStatus.ActionPermitted;
}
}
}
The check-in policy has to be deployed to the local machines of anyone who is going to use it.
Check-in policies are not the same thing as server-side plugins.

CRM Plugin for Publish and Publish All messages

I was wondering if we can write plugins that get executed for messages like "publish" and "publish all" in Dynamics CRM (any version). if so can you share any sample references for the same or code snippets.
This is a plugin that works for Publish and PublishAll messages and it will log the event using an entity that I created for this purpose (you can change to do whatever you want).
When the event is Publish, the plugin uses the ParameterXml parameter (MSDN) to log which components are being published. In the case of the PublishAll message, this parameter is not present so there's no detail (which makes sense because you're publishing all).
public class PublishPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
if (context.MessageName != "Publish" && context.MessageName != "PublishAll")
return;
string parameterXml = string.Empty;
if (context.MessageName == "Publish")
{
if (context.InputParameters.Contains("ParameterXml"))
{
parameterXml = (string)context.InputParameters["ParameterXml"];
}
}
CreatePublishAuditRecord(service, context.MessageName, context.InitiatingUserId, parameterXml);
}
private void CreatePublishAuditRecord(IOrganizationService service, string messageName, Guid userId, string parameterXml)
{
Entity auditRecord = new Entity("fjo_publishaudit");
auditRecord["fjo_message"] = messageName;
auditRecord["fjo_publishbyid"] = new EntityReference("systemuser", userId);
auditRecord["fjo_publishon"] = DateTime.Now;
auditRecord["fjo_parameterxml"] = parameterXml;
service.Create(auditRecord);
}
}
This is how it looks in CRM:
You can download the plugin project and CRM solution from my GitHub.
See here for a list of valid Dynamics CRM messages. Publish and PublishAll are both listed. They're also valid in all version of CRM from 2011 onward.
https://msdn.microsoft.com/en-us/library/gg328576.aspx
Just register your plugin like any other but use Publish or PublishAll for the message and leave the Entity as blank.
In the case of Publish, it seems by looking at the documentation that you can't narrow down which entity is being published. You'll have to take a look at what the Input Parameters give you to see if you can work out which entity you're dealing with, if you need it.

Resources