Translate

Home > 2018

2018

SQL Reporting Services 2017

Wednesday, May 2, 2018 Category : 0

https://github.com/Microsoft/Reporting-Services/tree/master/CustomSecuritySample


Reporting Services Custom Security Sample for Power BI Report Server and SQL Reporting Services 2017

This project contains a sample and the steps that allow you to deploy a custom security extension to SQL Reporting Services 2017 or Power BI Report Server.

Synopsis

Custom Authentication in SSRS and Power BI Report Server

SSRS 2016 introduced a new portal to host new OData APIs and host new report workloads such as mobile reports and KPIS. This new portal relies in newer technologies and is isolated from the familiar ReportingServicesService by running in a separate process. This process is not an ASP.NET hosted application and as such breaks assumptions from existing custom security extensions. Moreover, the current interfaces for custom security extensions don't allow for any external context to be passed-in, leaving implementers with the only choice to inspect well-known global ASP.NET Objects, this required some changes to the interface.

What Changed?

A new interface is introduced that can be implemented which provides an IRSRequestContext providing the more common properties used by extensions to make decisions related to authentication. In previous version ReportManager was the front-end and could be configured with its own custom login page, in SSRS2016 only one page hosted by reportserver is supported and should authenticate to both applications.
In previous versions extensions, could rely on a common assumption that ASP.NET objects would be readily available, since the new portal does not run in asp.net the extension might hit issues with objects being NULL. The most generic example is accessing HttpContext.Current to read request information such as headers and cookies. In order to allow extensions to make the same decisions we introduced a new method in the extension that provides request information and is called when authenticating from the portal.
Extensions should implement the IAuthenticationExtension2 interface to leverage this. The extensions will need to implement both versions of GetUserInfo method, as is called by the reportserver context and other used in webhost process. The sample below shows one of the simple implementations for the portal where the identity resolved by the reportserver is the one used.
public void GetUserInfo(IRSRequestContext requestContext, out IIdentity userIdentity, out IntPtr userId)
    {
        userIdentity = null;
        if (requestContext.User != null)
        {
            userIdentity = requestContext.User;
        }
        
        // initialize a pointer to the current user id to zero
        userId = IntPtr.Zero;
   }

Implementation

Step 1: Creating the UserAccounts Database

The sample includes a database script, Createuserstore.sql, that enables you to set up a user store for the Forms sample in a SQL Server database. Script is in the CustomSecuritySample\Setup folder.
  • To create the UserAccounts database
  • Open SQL Server Management Studio, and then connect to your local instance of SQL Server.
  • Locate the Createuserstore.sql SQL script file. The script file is contained within the sample project files.
  • Run the query to create the UserAccounts database.
  • Exit SQL Server Management Studio.

Step 2: Building the Sample

You must first compile and install the extension. The procedure assumes that you have installed Reporting Services to the default location: C:\Program Files\Microsoft Power BI Report Server\PBIRS\ReportServer\ or C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer. This location will be referred to throughout the remainder of this topic as <install>.
If you have not already created a strong name key file, generate the key file using the following instructions.
To generate a strong name key file
  • Open a Microsoft Visual Studio prompt and point to .Net Framework 4.0.
  • Use the change directory command (CD) to change the current directory of the command prompt window to the folder where the project is saved.
  • At the command prompt, run the following command to generate the key file: sn -k SampleKey.snk .
To compile the sample using Visual Studio
  • Open CustomSecuritySample.sln in Microsoft Visual Studio.
  • In Solution Explorer, select the CustomSecuritySample project.
  • Look at the CustomSecuritySample project's references. If you do not see Microsoft.ReportingServices.Interfaces.dll, then complete the following steps:
  • On the Project menu, click Add Reference. The Add References dialog box opens.
  • Click the .NET tab.
  • Click Browse, and find Microsoft.ReportingServices.Interfaces on your local drive. By default, the assembly is in the <install>\ReportServer\bin directory. Click OK. The selected reference is added to your project.
  • On the Build menu, click Build Solution.
Debugging
To debug the extension, you might want to attach the debugger to both ReportingServicesService.exe and Microsoft.ReportingServices.Portal.Webhost.exe. And add breakpoints to the methods implementing the interface IAuthenticationExtension2.

Step 3: Deployment and Configuration

The basic configurations needed for custom security extension are the same as previous releases. Following changes are needed in for web.config and rsreportserver.config present in the ReportServer folder. There is no longer a separate web.config for the reportmanager, the portal will inherit the same settings as the reportserver endpoint.
To deploy the sample
  • Copy the Logon.aspx page to the <install>\ReportServer directory.
  • Copy Microsoft.Samples.ReportingServices.CustomSecurity.dll and Microsoft.Samples.ReportingServices.CustomSecurity.pdb to the <install>\ReportServer\bin directory.
  • Copy Microsoft.Samples.ReportingServices.CustomSecurity.dll and Microsoft.Samples.ReportingServices.CustomSecurity.pdb to the <install>\Portal directory.
  • Copy Microsoft.Samples.ReportingServices.CustomSecurity.dll and Microsoft.Samples.ReportingServices.CustomSecurity.pdb to the <install>\PowerBI directory. (This only needs to be done for Power BI Report Server.)
If a PDB file is not present, it was not created by the Build step provided above. Ensure that the Project Properties for Debug/Build is set to generate PDB files.
Modify files in the ReportServer Folder
  • To modify the RSReportServer.config file.
  • Open the RSReportServer.config file with Visual Studio or a simple text editor such as Notepad. RSReportServer.config is located in the <install>\ReportServer directory.
  • Locate the <AuthenticationTypes> element and modify the settings as follows:
    <Authentication>
     <AuthenticationTypes> 
      <Custom/>
     </AuthenticationTypes>
     <RSWindowsExtendedProtectionLevel>Off</RSWindowsExtendedProtectionLevel>
     <RSWindowsExtendedProtectionScenario>Proxy</RSWindowsExtendedProtectionScenario>
     <EnableAuthPersistence>true</EnableAuthPersistence>
    </Authentication>
  • Locate the <Security> and <Authentication> elements, within the <Extensions> element, and modify the settings as follows:
    <Security>
     <Extension Name="Forms" Type="Microsoft.Samples.ReportingServices.CustomSecurity.Authorization, Microsoft.Samples.ReportingServices.CustomSecurity" >
     <Configuration>
      <AdminConfiguration>
       <UserName>username</UserName>
      </AdminConfiguration>
     </Configuration>
     </Extension>
    </Security>
    <Authentication>
     <Extension Name="Forms" Type="Microsoft.Samples.ReportingServices.CustomSecurity.AuthenticationExtension,Microsoft.Samples.ReportingServices.CustomSecurity" />
    </Authentication> 
Note: If you are running the sample security extension in a development environment that does not have a Secure Sockets Layer (SSL) certificate installed, you must change the value of the <UseSSL> element to False in the previous configuration entry. We recommend that you always use SSL when combining Reporting Services with Forms Authentication.
To modify the RSSrvPolicy.config file
  • You will need to add a code group for your custom security extension that grants FullTrust permission for your extension. You do this by adding the code group to the RSSrvPolicy.config file.
  • Open the RSSrvPolicy.config file located in the <install>\ReportServer directory.
  • Add the following <CodeGroup> element after the existing code group in the security policy file that has a URL membership of $CodeGen as indicated below and then add an entry as follows to RSSrvPolicy.config. Make sure to change the below path according to your ReportServer installation directory:
    <CodeGroup
     class="UnionCodeGroup"
     version="1"
     Name="SecurityExtensionCodeGroup" 
     Description="Code group for the sample security extension"
     PermissionSetName="FullTrust">
    <IMembershipCondition 
     class="UrlMembershipCondition"
     version="1"
     Url="C:\Program Files\Microsoft Power BI Report Server\PBIRS\ReportServer\bin\Microsoft.Samples.ReportingServices.CustomSecurity.dll"/>
    </CodeGroup>
Note: For simplicity, the Forms Authentication Sample is weak-named and requires a simple URL membership entry in the security policy files. In your production security extension implementation, you should create strong-named assemblies and use the strong name membership condition when adding security policies for your assembly. For more information about strong-named assemblies, see the Creating and Using Strong-Named Assemblies topic on MSDN.
To modify the Web.config file for Report Server
  • Open the Web.config file in a text editor. By default, the file is in the <install>\ReportServer directory.
  • Locate the <identity> element and set the Impersonate attribute to false.
    <identity impersonate="false" />
  • Locate the <authentication> element and change the Mode attribute to Forms. Also, add the following <forms> element as a child of the <authentication> element and set the loginUrl, name, timeout, and path attributes as follows:
    <authentication mode="Forms">
     <forms loginUrl="logon.aspx" name="sqlAuthCookie" timeout="60" path="/"></forms>
    </authentication> 
  • Add the following <authorization> element directly after the <authentication> element.
    <authorization> 
    <deny users="?" />
    </authorization> 
This will deny unauthenticated users the right to access the report server. The previously established loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the Logon.aspx page.

Step 4: Generate Machine Keys

Using Forms authentication requires that all report server processes can access the authentication cookie. This involves configuring a machine key and decryption algorithm - a familiar step for those who had previously setup SSRS to work in scale-out environments.
Generate and add <MachineKey> under <Configuration> in your RSReportServer.config file.
<MachineKey ValidationKey="[YOUR KEY]" DecryptionKey="[YOUR KEY]" Validation="AES" Decryption="AES" />
Check the casing of the attributes, it should be Pascal Casing as the example above
There is not need for a <system.web> entry
You should use a validation key specific for you deployment, there are several tools to generate the keys such as Internet Information Services Manager (IIS)

Step 5: Configure Passthrough cookies

The new portal and the reportserver communicate using internal soap APIs for some of its operations. When additional cookies are required to be passed from the portal to the server the PassThroughCookies properties is still available. More Details: https://msdn.microsoft.com/en-us/library/ms345241.aspx In the rsreportserver.config file add following under <UI>
<UI>
   <CustomAuthenticationUI>
      <PassThroughCookies>
         <PassThroughCookie>sqlAuthCookie</PassThroughCookie>
      </PassThroughCookies>
   </CustomAuthenticationUI>
</UI>


Other resouce

Online Machine Key Generator
http://www.a2zmenu.com/utility/machine-key-generator.aspx


Sample Customer Authentication project
 https://www.dropbox.com/s/26sbk4jz7rd65ou/Reporting-Services-master.zip?dl=0

Server Upgradition or migration help :
https://healmyscm.wordpress.com/2018/03/21/the-report-server-cant-access-or-use-the-encryption-key-you-might-need-to-add-the-server-to-the-scale-out-group/

Error Log for 500 error

SQL Report Server: No DSN present in configuration file



After you have installed or added a report server to SQL, the report server is not yet setup. You still have to do the following to complete the setup.
  1. Open the Reporting Services Configuration Manager
  2. Go to the Database section in the Menu and add a database to be used by the Reporting service
  3. On the same page enter the Reporting database credential
  4. Go to the web service url and specify the name of a virtual directory and a TCP port to be used. Do not use a port that is already in use, e.g port 80 may be already used by Sharepoint or MIM Portal.
  5. Go to the reportmanager url and specify a virtual directory name to be used.

Error : Symmetric key not initialized 

 Encrypted data is not accessible| RequestID = s_508ef2f9-33ae-46d7-95b2-048a81069541 Microsoft.BIServer.HostingEnvironment.Cryptography.Exceptions.SymmetricKeyNotInitializedException: Symmetric key not initialized
   at Microsoft.BIServer.Configuration.Key.KeyRepository.GetAnnouncedKeyResults(Guid installationId)
   at Microsoft.BIServer.Configuration.Key.KeyRepository.ReloadEncryptedSymmetricKey()
   at Microsoft.BIServer.Management.WebApi.Controllers.StateController.ReloadEncryptedSymmetricKey(ISqlAccess sqlAccess, Byte[]& encryptedSymmetricKey, DatabaseValidationStatus databaseValidationStatus)


Solution i got so far : 


Error : The permissions granted to user 'Anonymous' are insufficient for performing this operation. (rsAccessDenied)

Solution : 




Jquery Image to Base64 Convert ,For Servier side upload

Thursday, April 26, 2018 Category : 0


var file1;
            if (document.getElementById("inputFile").files.length > 0) {
                file1 = document.getElementById("inputFile").files[0];


                var reader = new FileReader();
                reader.readAsDataURL(file1);
                var image;
                reader.onloadend = function (e) {
                    var Image64= e.target.result;
                 // post to server
                   

                }
            }

ASP.NET Core AngularJs/Jquery File Upload

Category : 0

 public class FileInputModel
    {
        public IFormFile FileToUpload { get; set; }
        public string UserId { get; set; }
    }


API Class

 public class FileUploadController : Controller
    {
        [HttpPost]
        [Route("api/fileupload/CustomerExcelUpload2")]
   
        public IActionResult CustomerExcelUpload2(FileInputModel file)
        {

        }



}


For AngularJs :


return $http({
            url: serviceBasePath + '/api/fileupload',
            method: 'POST',
            //data: JSON.stringify(data),
            processData: false,
            contentType: false,
            data: (data),
            headers: { 'content-type': undefined }
            , transformRequest: angular.identity
        }).success(function (d) {
            defer.resolve(d);
        }).error(function (error) {
            defer.reject();
            ShowMsg(error.ExceptionMessage);
        })
            ;



Jquery



 $.ajax(
            {
                url:  'http://localhost:8094/api/fileupload/CustomerExcelUpload',
               data: formData,
                processData: false,
                contentType: false,
                type: "POST",
                success: function (data) {
                    alert("Files Uploaded!");
              }
            }
       );

Dell USB Drive the disk is write protected pen drive

Thursday, March 15, 2018 Category : 2



My Solution obtain by following link

http://www.techunboxed.com/2016/09/how-to-disable-write-protection-on-dell.html

which is desribed in comment on above link article

Round 5:
(0. Insert a new DELL U3-8GDSTS flash drive into a usb port - I used a usb2.0 port)
1. Download SMI MPTool V2.5.36 v7 from here: http://flashboot.ru/files/file/445/ (Direct Download: http://flashboot.ru/files/file/445/download/sm3267_v2536_aa3/)
2. Extract the RAR and open the "sm32Xtest_V36-7.exe" as admin
3. Press "Setting" - Password: 320
4. Load the "default.ini" or download the content of my already customized "DELL_ROUND_5.ini" (https://pastebin.com/vv06mB8V) and load it.
4.1. When loading the "default.ini", under the tab "Capacity Setting" change the "Bad Block" value from 44 to 60.
5. Press "OK" to close the settings, click on "Scan USB" (or press F5), wait for the flash drive to show up and then hit "Start" - after 30 to 60 seconds you'll have an unlocked DELL 8GB flash drive ;)

Cheers!

 here is some other reference for different scenario

https://www.dell.com/community/Storage-Drives-Media/Unable-to-format-Dell-USB/td-p/4659496
https://www.dell.com/community/Storage-Drives-Media/Unable-to-format-Dell-USB/td-p/4659496

I have maintain a download link of all software uses in all those article

https://drive.google.com/open?id=1jUCZcXOcPve78K9IEObfHFz-PBeX9UZM

FIK.DAL

Friday, March 2, 2018 Category : , 0

Welcome to the FIK.DAL wiki!

This Library develop  for reducing to write simple query which is need to write frequently, when developing an
application.
A Simple SQL Query Generator Using ADO.NET Provider with SqlClient. Some Developer want's to develop through own query, rather then entity framework. Then it is useful to reduce query generation task.


In the above picture shown this library what can perfom.

Above this picture shown an sample test client for this library.


Above this picture shown using this library for easy insert query.

Above this picture shows when need to insert data throgh various model . with insert or update.
when using update then if  you need to increase/decrease a field value with current value then
use a  + or - sign ,on selectiveProperty Parameter .

This is the final test output

https://github.com/imamulkarim/FIK.DAL

SQL Server Deafult Port Open For Windows

Sunday, February 25, 2018 Category : 0

For Cmd

@echo ========= SQL Server Ports ===================
@echo Enabling SQLServer default instance port 1433
netsh firewall set portopening TCP 1433 "SQLServer"
@echo Enabling Dedicated Admin Connection port 1434
netsh firewall set portopening TCP 1434 "SQL Admin Connection"
@echo Enabling conventional SQL Server Service Broker port 4022
netsh firewall set portopening TCP 4022 "SQL Service Broker"
@echo Enabling Transact-SQL Debugger/RPC port 135
netsh firewall set portopening TCP 135 "SQL Debugger/RPC"
@echo ========= Analysis Services Ports ==============
@echo Enabling SSAS Default Instance port 2383
netsh firewall set portopening TCP 2383 "Analysis Services"
@echo Enabling SQL Server Browser Service port 2382
netsh firewall set portopening TCP 2382 "SQL Browser"
@echo ========= Misc Applications ==============
@echo Enabling HTTP port 80
netsh firewall set portopening TCP 80 "HTTP"
@echo Enabling SSL port 443
netsh firewall set portopening TCP 443 "SSL"
@echo Enabling port for SQL Server Browser Service's 'Browse' Button
netsh firewall set portopening UDP 1434 "SQL Browser"
@echo Allowing multicast broadcast response on UDP (Browser Service Enumerations OK)
netsh firewall set multicastbroadcastresponse ENABLE

For PowerShell version of the script

Write-host ========= SQL Server Ports ===================

Write-host Enabling SQLServer default instance port 1433

#netsh firewall set portopening TCP 1433 "SQLServer"

New-NetFirewallRule -DisplayName "Allow inbound TCP Port 1433" –Direction inbound –LocalPort 1433 -Protocol TCP -Action Allow

New-NetFirewallRule -DisplayName "Allow outbound TCP Port 1433" –Direction outbound –LocalPort 1433 -Protocol TCP -Action Allow

Write-host Enabling Dedicated Admin Connection port 1434

#netsh firewall set portopening TCP 1434 "SQL Admin Connection"

New-NetFirewallRule -DisplayName "Allow inbound TCP Port 1434" -Direction inbound –LocalPort 1434 -Protocol TCP -Action Allow

New-NetFirewallRule -DisplayName "Allow outbound TCP Port 1434" -Direction outbound –LocalPort 1434 -Protocol TCP -Action Allow

Write-host Enabling conventional SQL Server Service Broker port 4022

#netsh firewall set portopening TCP 4022 "SQL Service Broker"

New-NetFirewallRule -DisplayName "Allow inbound TCP Port 4022" -Direction inbound –LocalPort 4022 -Protocol TCP -Action Allow

New-NetFirewallRule -DisplayName "Allow outbound TCP Port 4022" -Direction outbound –LocalPort 4022 -Protocol TCP -Action Allow

Write-host Enabling Transact-SQL Debugger/RPC port 135

#netsh firewall set portopening TCP 135 "SQL Debugger/RPC"

New-NetFirewallRule -DisplayName "Allow inbound TCP Port 135" -Direction inbound –LocalPort 135 -Protocol TCP -Action Allow

New-NetFirewallRule -DisplayName "Allow outbound TCP Port 135" -Direction outbound –LocalPort 135 -Protocol TCP -Action Allow

Write-host ========= Analysis Services Ports ==============

Write-host Enabling SSAS Default Instance port 2383

#netsh firewall set portopening TCP 2383 "Analysis Services"

New-NetFirewallRule -DisplayName "Allow inbound TCP Port 2383" -Direction inbound –LocalPort 2383 -Protocol TCP -Action Allow

New-NetFirewallRule -DisplayName "Allow outbound TCP Port 2383" -Direction outbound –LocalPort 2383 -Protocol TCP -Action Allow

Write-host Enabling SQL Server Browser Service port 2382

#netsh firewall set portopening TCP 2382 "SQL Browser"

New-NetFirewallRule -DisplayName "Allow inbound TCP Port 2382" -Direction inbound –LocalPort 2382 -Protocol TCP -Action Allow

New-NetFirewallRule -DisplayName "Allow outbound TCP Port 2382" -Direction outbound –LocalPort 2382 -Protocol TCP -Action Allow

Write-host ========= Misc Applications ==============

Write-host Enabling HTTP port 80

#netsh firewall set portopening TCP 80 "HTTP"

New-NetFirewallRule -DisplayName "Allow inbound TCP Port 80" -Direction inbound –LocalPort 80 -Protocol TCP -Action Allow

New-NetFirewallRule -DisplayName "Allow outbound TCP Port 80" -Direction outbound –LocalPort 80 -Protocol TCP -Action Allow

Write-host Enabling SSL port 443

#netsh firewall set portopening TCP 443 "SSL"

New-NetFirewallRule -DisplayName "Allow inbound TCP Port 443" -Direction inbound –LocalPort 443 -Protocol TCP -Action Allow

New-NetFirewallRule -DisplayName "Allow outbound TCP Port 443" -Direction outbound –LocalPort 443 -Protocol TCP -Action Allow

Write-host Enabling port for SQL Server Browser Service's 'Browse

#netsh firewall set portopening UDP 1434 "SQL Browser"

New-NetFirewallRule -DisplayName "Allow inbound UDP Port 1434" -Direction inbound –LocalPort 1434 -Protocol UDP -Action Allow

New-NetFirewallRule -DisplayName "Allow outbound UDP Port 1434" -Direction outbound –LocalPort 1434 -Protocol UDP -Action Allow




If Both SQL 2008 & SQL 2014 , OR Any Different two or more version. Then remote pc browse
only work for one version. then we need to manually add port settings for one or more sql tcp port.

Shown in below Screen shot .


in my case Port is default set for sql 2008

 
Then i have set manually port for sql 14 and add  to the firewall exception.

@echo Enabling SQLServer default instance port 1533
netsh firewall set portopening TCP 1533 "SQLServer"



C# HttpWebRequest FormData post and return Json

Wednesday, January 24, 2018 Category : , 0


        public static Result POSTFormData(string url, string identifier, string FormData)
        {
            // Setup the POST data
            //string poststring = String.Format("qrCodeData=90320388203195564382");
            Result result = new Result();
            try
            {

                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);

                httpRequest.Method = "POST";
                httpRequest.ContentType = "application/x-www-form-urlencoded";
                httpRequest.Headers.Add("secret", identifier);


                // Convert the post string to a byte array
                byte[] bytedata = System.Text.Encoding.UTF8.GetBytes(FormData);
                httpRequest.ContentLength = bytedata.Length;

                // Create the stream
                Stream requestStream = httpRequest.GetRequestStream();
                requestStream.Write(bytedata, 0, bytedata.Length);
                requestStream.Close();

                // Get the response from remote server
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                using (StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        sb.Append(line);
                    }
                }

                result.ResultState = true;
                result.JsonString = sb.ToString();

            }
            catch (Exception ex)
            {
                result.ResultState = false;
                result.SqlError = ex.Message;
            }

            return result;
        }



            object theImg = dt.Rows[0]["Picture"];
if (!DBNull.Equals(theImg, DBNull.Value) && ((byte[])theImg).Length > 0)
            {
                 pictureBox1.BackgroundImage = new ImageHelper().ByteToImage((byte[])theImg);
}

C# Image , Byte , URL To Image Convert

Category : 0

    public class ImageHelper
    {
        public byte[] ImageToByte(Image imageIn)
        {

            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }

        public Image ByteToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        public Image GenerateThumbnailImage(string imgUrl)
        {
            Image imgThumb = null;
            try
            {
                Image image = null;
                if (imgUrl != String.Empty)
                    image = Image.FromFile(imgUrl);

                if (image != null)
                {
                    imgThumb = image.GetThumbnailImage(130, 170, null, new IntPtr());
                    //this.Refresh();
                }
                return imgThumb;
            }
            catch
            {              
                return imgThumb;
            }
        }

    }

SQL Store Procedure To Class Wrapper

Wednesday, January 3, 2018 Category : 0



DECLARE @sql NVARCHAR(MAX) = N'EXEC ShopMenu_GermanClub.dbo.SP_ReportRM_PO_Challan ww,admin,Y;';

--SELECT name, system_type_name
--    FROM sys.dm_exec_describe_first_result_set(@sql, NULL, 1) AS col


declare @TableName sysname = 'SP_ReportRM_PO_Challan'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select
        replace(col.name, ' ', '_') ColumnName,
       
        case --col.system_type_name
            WHEN (CHARINDEX('nvarchar',system_type_name)>0) then 'string'
            when (system_type_name='bigint') then 'long'
            when (system_type_name='binary') then 'byte[]'
            when (system_type_name='bit') then 'bool'
            when (system_type_name='char') then 'string'
            when (system_type_name='date') then 'DateTime'
            when (system_type_name='datetime') then 'DateTime'
            when (system_type_name='datetime2') then 'DateTime'
            when (system_type_name='datetimeoffset') then 'DateTimeOffset'
            when (CHARINDEX('decimal',system_type_name)>0) then 'decimal'
            when (system_type_name='float') then 'float'
            when (system_type_name='image') then 'byte[]'
            when (system_type_name='int') then 'int'
            when (system_type_name='money') then 'decimal'
            when (system_type_name='nchar') then 'string'
            when (system_type_name='ntext') then 'string'
            when (CHARINDEX('numeric',system_type_name)>0) then 'decimal'
            when (system_type_name='real') then 'double'
            when (system_type_name='smalldatetime') then 'DateTime'
            when (system_type_name='smallint') then 'short'
            when (system_type_name='smallmoney') then 'decimal'
            when (system_type_name='text') THEN 'string'
            when (system_type_name='time') then 'TimeSpan'
            when (system_type_name='timestamp') then 'DateTime'
            when (system_type_name='tinyint') then 'byte'
            when (system_type_name='uniqueidentifier') then 'Guid'
            when (system_type_name='varbinary') then 'byte[]'
            when (system_type_name='varchar') then 'string'
            ELSE ('UNKNOWN_') + col.system_type_name
        end ColumnType,
        case
            when col.is_nullable = 1 and col.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier')
            then '?'
            else ''
        end NullableSign
    -- name, system_type_name
    FROM sys.dm_exec_describe_first_result_set(@sql, NULL, 1) AS col

) t
--order by ColumnId

set @Result = @Result  + '
}'

print @Result

Powered by Blogger.