SQL Server,C#.Net,Crystal Report Solution
SQL Server,C#.Net,Crystal Report Solution
Friday, August 27, 2021
Wednesday, March 17, 2021
SQL Server 2017 Features
1. TRANSLATE: It basically takes a string as input and then translates the characters with some new characters, see below Syntax:
TRANSLATE ( inputString, characters, translations)
For Example : SELECT TRANSLATE ('4*{1+1}/[81-41]','[]{}','()()')
Output : 4*(1+1)/(81-41)
This function is work as REPLACE function. but TRANSLATE function is easier to use and also useful when we have to replace more than one value in the string.
2. CONCATE_WS: It simply concats all input arguments with the specified input delimiter.
Syntax : CONCAT_WS ( separator, argument1, argument1, [argumentN]… )
For Example :
SELECT CONCAT_WS(',','Count', '1', '2', '3', '4' ) AS counter;
Output : nikhil, hardik, nilesh, sandip
3. TRIM: It simply works as the C# trim function, removes all spaces from start and end of the string.
Syntax: TRIM(inputString)
For Example :
SELECT TRIM(' Samlpe demo ') AS result;
Output : Samlpe demo
It removes only space from start and ends, not between the word and string.
4. String_AGG: It will used to create single comma-separated string.
Syntax: String_AGG(column name,',')
For Example :
create table names ( [name] varchar(50) )go
insert into names values ('1'),('2'),('3'),('4')
Here I have used stuff
select stuff((select ',' + [name] as [text()]
from names for xml path('')),1,1,'')
Here I have used string_agg
select string_agg([name],',') from names
Output : 1,2,3,4
Pagination with OFFSET and FETCH in SQL Query
Pagination with OFFSET and FETCH in SQL Server.
In the real world, we load the data on the front from the database one time and load it into memory via data table or in some other form (main table and other supported tables) and
then loop through individual records in Parallel For Each for better performance. However, in some cases, if the data load is huge,
we may end up having memory issues loading all the records on the front so weload each individual record inside the loop in SQL which could potentially affect the performance.
Sample :
SELECT First_Name + ' ' + Last_Name FROM REgistration
ORDER BY First_Name OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;
In this example, it will skip the first 10 rows and return the next 5 rows.
Limitations while Using OFFSET-FETCH
ORDER BY is mandatory to use OFFSET and FETCH clause.
OFFSET clause is mandatory with FETCH. You can never use, ORDER BY … FETCH.
TOP cannot be combined with OFFSET and FETCH in the same query expression.
The OFFSET/FETCH row count expression can be any arithmetic, constant, or parameter expression that will return an integer value. The row count expression does not support scalar sub-queries.
How To See Logs Of Dropped Tables From The Database in Microsoft SQL SERVER
Here, I will explain you how you can see logs of users.
Step 2 : Create a new table.
sql server user login history
SELECT *
FROM master.dbo.sysprocesses sp
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid
go
SELECT
c.session_id,
c.net_transport,
s.host_name,
s.program_name,
s.nt_user_name,
c.connect_time,
s.client_interface_name,
c.client_net_address,
c.local_net_address,
s.login_name,
s.nt_domain,
s.login_time
FROM sys.dm_exec_connections AS c
JOIN sys.dm_exec_sessions AS s
ON c.session_id = s.session_id;
go
SELECT *
FROM sys.dm_exec_sessions
WHERE database_id > 0 -- OR 4 for user DBs
--GROUP BY database_id, login_name, status, host_name, program_name, nt_domain, nt_user_name;
Monday, February 10, 2020
Sql server Function Name Find
SELECT OBJECT_NAME(sed.referencing_id) AS referencing_entity_name,
o.type_desc AS referencing_desciption,
COALESCE(COL_NAME(sed.referencing_id, sed.referencing_minor_id), '(n/a)') AS referencing_minor_id,
sed.referencing_class_desc, sed.referenced_class_desc,
sed.referenced_server_name, sed.referenced_database_name, sed.referenced_schema_name,
sed.referenced_entity_name,
COALESCE(COL_NAME(sed.referenced_id, sed.referenced_minor_id), '(n/a)') AS referenced_column_name,
sed.is_caller_dependent, sed.is_ambiguous
-- from the two system tables sys.sql_expression_dependencies and sys.object
FROM sys.sql_expression_dependencies AS sed
INNER JOIN sys.objects AS o ON sed.referencing_id = o.object_id
-- on the function dbo.ufnGetProductDealerPrice
WHERE sed.referencing_id = OBJECT_ID('dbo.ufnTest');
go
SELECT sm.object_id,
OBJECT_NAME(sm.object_id) AS object_name,
o.type,
o.type_desc,
sm.definition,
sm.uses_ansi_nulls,
sm.uses_quoted_identifier,
sm.is_schema_bound,
sm.execute_as_principal_id
-- using the two system tables sys.sql_modules and sys.objects
FROM sys.sql_modules AS sm
JOIN sys.objects AS o ON sm.object_id = o.object_id
-- from the function 'dbo.ufnGetProductDealerPrice'
WHERE sm.definition like '%ufnTest%'
ORDER BY o.type;
Friday, October 4, 2019
.NET Annotated Monthly | October 2019
.NET news
.NET tutorials and tips
Events, community and culture
- Techorama Netherlands
- Dotnet Days [Rachel speaking]
- DevReach [Rachel speaking]
- .NET Fest [Rachel, Mattihas speaking]
- GoTech World [Maarten speaking]
Random, interesting, and cool stuff
And finally…
- Async Streams – A Look at New Language Features in C# 8 – by Matthias Koch
- Developing Xamarin applications in Rider – by Maarten Balliauw
- Build HTML and JavaScript apps using Rider – by Rachel Appel
- Find your perfect C# style using Rider – by Rachel Appel
- Better Xamarin development with Rider on Mac – Maarten Balliauw hosts Dylan Berry in this Webinar
Tuesday, December 18, 2018
How To Implement NLog With WebAPI In Asp.Net(C#).
NLog is a flexible and free logging platform for various .NET platforms, including .NET standard. NLog is easy to apply and it includes several targets (database, file, event viewer).
Which platform support it?
.NET Framework 3.5, 4, 4.5, 4.6 & 4.7
.NET Framework 4 client profile
Xamarin Android
Xamarin iOS
Windows Phone 8
Silver light 4 and 5
Mono 4
ASP.NET 4 (NLog.Web package)
ASP.NET Core (NLog.Web.AspNetCore package)
.NET Core (NLog.Extensions.Logging package)
.NET Standard 1.x - NLog 4.5
.NET Standard 2.x - NLog 4.5
UWP - NLog 4.5
There are several log levels.
Fatal : Something terrible occurred; the application is going down
Error : Something fizzled; the application might possibly proceed
Warn : Something surprising; the application will proceed
Info : Normal conduct like mail sent, client refreshed profile and so on.
Debug : For troubleshooting; the executed question, the client confirmed, session terminated
Trace : For follow troubleshooting; start technique X, end strategy X
Where we can log?
Console
Database
Event Viewer Log
Files
Network
Implementation of NLog
Step 1 : Open Visual Studio. Select File > New > Project.
Step 2 : Select Web> ASP.NET Web Application > Give your project name "NLogTestApp", and then click OK.
Step 3 : Select Web API and click OK.
Step 4 : Now, we add NLog in our project. Right-click on your project solution, click on "Manage NugGet Packages". Click on the "Browse" link button and in the search box, type nlog. It will show you NLogDll as shown below. Just install this dll.
After that, when you click "Install", you will get the following window, i.e., Preview Changes.
In this popup window, click the OK button. After it is successfully installed, you will get the Nlog dll in your project reference.
Step 5 : Now, add the following code to your config file.
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="${basedir}/MyLogs/${date:format=yyyy-MM-dd}-api.log" />
<target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source=" My Custom Api Services" />
<target name="database" type="Database" connectionString="Data Source=SRKSUR5085LT\SQLEXPRESS;initial catalog=NLog;user id=sa;password=OPTICAL;MultipleActiveResultSets=True;">
<commandText> insert into ExceptionLog ([TimeStamp],[Level],Logger, [Message], UserId, Exception, StackTrace) values (@TimeStamp, @Level, @Logger, @Message, case when len(@UserID) = 0 then null else @UserId end, @Exception, @StackTrace); </commandText>
<parameter name="@TimeStamp" layout="${date}" />
<parameter name="@Level" layout="${level}" />
<parameter name="@Logger" layout="${logger}" />
<parameter name="@Message" layout="${message}" />
<parameter name="@UserId" layout="${mdc:user_id}" />
<parameter name="@Exception" layout="${exception}" />
<parameter name="@StackTrace" layout="${stacktrace}" />
<dbProvider>System.Data.SqlClient</dbProvider>
</target>
</targets>
<rules>
<!-- I am adding my 3 logging rules here -->
<logger name="*" minlevel="Debug" writeTo="database" />
<logger name="*" minlevel="Trace" writeTo="logfile" />
<logger name="*" minlevel="Trace" writeTo="eventlog" />
</rules>
</nlog>
We will targeting to log into three places.
database
txt file
Event Viewer
Your config look like below.
Step 6 : We need to create our DB Script as shown below
CREATE TABLE [dbo].[exceptionlog]
(
[id] [INT] IDENTITY(1, 1) NOT NULL,
[timestamp] [DATETIME] NOT NULL,
[level] [VARCHAR](100) NOT NULL,
[logger] [VARCHAR](1000) NOT NULL,
[message] [VARCHAR](3600) NOT NULL,
[userid] [INT] NULL,
[exception] [VARCHAR](3600) NULL,
[stacktrace] [VARCHAR](3600) NULL,
CONSTRAINT [PK_ExceptionLog] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (
pad_index = OFF, statistics_norecompute = OFF, ignore_dup_key = OFF,
allow_row_locks = on, allow_page_locks = on) ON [PRIMARY]
)
ON [PRIMARY]
Step 7 : Now, go to your home controller and add following code in index method.
using NLog;
using System;
using System.Web.Mvc;
namespace NLogTestApp.Controllers
{
public class HomeController : Controller
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public ActionResult Index()
{
ViewBag.Title = "Home Page";
logger.Info("Hello we have visited the Index view" + Environment.NewLine + DateTime.Now);
return View();
}
}
}
Now, run the application.
data-ad-format="auto" And open your SQL. You will see the following logs inserted in your database.
You can see this in your Event Viewer.
You can see the following in your text file.
When you are working with WEPAPI that time NLog is very useful and easy to apply.
Tuesday, February 13, 2018
How to convert records in a table to XML format using T-SQL
How to get list of all Folder in network sharing path using SQL Server
Create Window Service Setup Using .bat file
Monday, February 12, 2018
Query For Calculate CPU Usage in SQL Server
Angular Project Demo
{{greeting}}
File Upload in Angular 2
Input Only Number in Iput Type in Angular 2
Passing Data To Component in Agular2 With Using Service
Sunday, January 21, 2018
Not Empty Table List In Sql Server
(
SELECT
SUM(row_count) AS [row_count],
OBJECT_NAME(OBJECT_ID) AS TableName
FROM
sys.dm_db_partition_stats
WHERE
index_id = 0 OR index_id = 1
GROUP BY
OBJECT_ID
)
SELECT *
FROM TableName
WHERE [row_count] > 0
Wednesday, January 10, 2018
Get Hour And minute, Second From Second in Sql Server
SET @Second1=ABS(@Second1)
DECLARE @ETIME AS VARCHAR(20)
SELECT @ETIME = RIGHT(CAST(@Second1 / 3600 AS VARCHAR(10)),7) + '.' +
RIGHT('0' + CAST((@Second1 / 60) % 60 AS VARCHAR(10)),2) + ':' + RIGHT('0' + CAST(@Second1 % 60 AS VARCHAR(2)),2)
SELECT @ETIME
Convert Minute To Hour in SQL Server function
(
@Second1 BIGINT=0
)
RETURNS TIME
AS
BEGIN
DECLARE @Res TIME =NULL
SET @Second1=ABS(@Second1)
DECLARE @ETIME AS VARCHAR(20)
SELECT @ETIME = RIGHT(CAST(@Second1 / 60 AS VARCHAR(10)),7) + '.' + RIGHT('0' + CAST((@Second1) % 60 AS VARCHAR(10)),2)
SELECT @RES= CAST(REPLACE(@ETIME,'.',':') AS TIME)
RETURN @RES
END
Convert Second to Hour in Sql Server function
(
@Second1 BIGINT=0
)
RETURNS TIME
AS
BEGIN
DECLARE @Res TIME =NULL
SET @Second1=ABS(@Second1)
DECLARE @ETIME AS VARCHAR(20)
SELECT @ETIME = RIGHT(CAST(@Second1 / 3600 AS VARCHAR(10)),7) + '.' +
RIGHT('0' + CAST((@Second1 / 60) % 60 AS VARCHAR(10)),2) + ':' + RIGHT('0' + CAST(@Second1 % 60 AS VARCHAR(2)),2)
SELECT @RES= CAST(REPLACE(@ETIME,'.',':') AS TIME)
RETURN @RES
END
Tuesday, January 9, 2018
Rotate image in asp.net
{
System.Drawing.Image img = System.Drawing.Image.FromFile(System.Web.Hosting.HostingEnvironment.MapPath("/images/") + Filename);
//Rotate the image in memory
img.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
System.IO.File.Delete(System.Web.Hosting.HostingEnvironment.MapPath("/images/" + FileNameNew));
//save the image out to the file
img.Save(System.Web.Hosting.HostingEnvironment.MapPath("/images/" + FileNameNew));
//release image file
img.Dispose();
}
Saturday, September 9, 2017
Split value using Charindex in SQL Server
OutPut => 11
Friday, June 23, 2017
Turning a Comma Separated string into individual rows in Sql Server
from Emp t
cross apply (select Code from dbo.Split(t.Data,',') ) x
Wednesday, May 24, 2017
Solve - How to show a string in indian rupees format in C#.net?
System.Globalization.CultureInfo info = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string StrAmt = dblAmt.ToString("N2", info);
txtAmt.Text = StrAmt;
Output := 1,34,600.00
Thursday, May 4, 2017
Find Tables With Foreign Key Constraint in SQL Server
SCHEMA_NAME(f.SCHEMA_ID) SchemaName,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName,
SCHEMA_NAME(o.SCHEMA_ID) ReferenceSchemaName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id
Monday, September 26, 2016
INI File Read and Write in C#.Net
- text file Read and Write in C#.Net
public class
File
{
private
string
filePath;
[DllImport(
"kernel32"
)]
private
static
extern
long
WritePrivateProfileString(
string
section,
string
key,
string
val,
string
filePath);
[DllImport(
"kernel32"
)]
private
static
extern
int
GetPrivateProfileString(
string
section,
string
key,
string
def,
StringBuilder retVal,
int
size,
string
filePath);
public
File(
string
filePath)
{
this
.filePath = filePath;
}
public
void
Write(
string
section,
string
key,
string
value)
{
WritePrivateProfileString(section, key, value.ToLower(),
this
.filePath);
}
public
string
Read(
string
section,
string
key)
{
StringBuilder SB =
new
StringBuilder(255);
int
i = GetPrivateProfileString(section, key,
""
, SB, 255,
this
.filePath);
return
SB.ToString();
}
public
string
FilePath
{
get
{
return
this
.filePath; }
set
{
this
.filePath = value; }
}
}