Wednesday, December 30, 2020

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to make it fast. Faster solution for large data is here: see below:



import { FixedSizeList as List } from 'react-window';
import Select, { createFilter } from 'react-select';

<Select 

                        value={this.state.selectedReport}

                        onChange={this.handleChangeReport}

                        filterOption={createFilter({ ignoreAccents: false })} // this makes it fast!

                        components={{ CustomMenu }}

                        options={Reports}

                        isClearable={true}


                    />




const CustomMenu = props => {

            

            const { Reports, children, maxHeight, getValue } = this.props;

            const [value] = getValue();



            return (

                <List

                    height={150}

                    itemCount={children.length}

                    itemSize={35}

                >

                    {({ index, style }) => <div style={style}>{children[index]}</div>}

                </List>

            );

        };



React - axios api call to render file using blob - pdf or excel or xls or xlsx - using Asp.net

 I was struggling to call API to get PDF/Excel files. I found complete solution which is working in all browsers. Here is the .net c# code:


[Route("api/queries")]

    [HttpGet]

    public string getFile()

    {

        WebClient Client = new WebClient();

        Client.UseDefaultCredentials = true;

        byte[] myDataBuffer = Client.DownloadData("URL");

        string DocumentPath = Convert.ToBase64String(myDataBuffer);

        return DocumentPath;

    }


And here is front end in React using axios and blob:


axios.get(fetchFileUrl)

            .then((response) => {

                var raw = window.atob(response.data);

                var uint8Array = new Uint8Array(raw.length);

                for (var i = 0; i < raw.length; i++) {

                    uint8Array[i] = raw.charCodeAt(i);

                }

                var newBlob = new Blob([uint8Array])

                if (window.navigator && window.navigator.msSaveOrOpenBlob) {

                    window.navigator.msSaveOrOpenBlob(newBlob, fileName + '.xlsx');

                    console.log('ie', '11');

                }

                else {

                    const data = window.URL.createObjectURL(newBlob);

                    var link = document.createElement('a');

                    link.href = data;

                    link.download = fileName + '.xlsx';

                    link.click();

                    link.remove();

                    setTimeout(function () {

                        // For Firefox it is necessary to delay revoking the ObjectURL

                        window.URL.revokeObjectURL(data);

                    }, 100);

                    

                    console.log('not ie', 'others');

                   

                } 


                console.log('end', new Date().toLocaleDateString("en-US") + ' ' + new Date().toLocaleTimeString("en-US"));

            }).catch((error) => console.log(error));

Monday, March 19, 2018

Microsoft Edge - SSRS URL does not refresh result render as PDF from Asp.net response.redirect

The problem started when I upgraded my operating system to Windows 10. It comes with Microsoft Edge. My Application was working perfect before. It was returning fresh result from SSRS as PDF. I was using following URL in response.redirect

http://servername/Reportserver?/SSRSRPT2RDL/Main&rs:Command=Render&rs:Format=PDF&year=2018&source=Menu

After upgrade, I have started receiving results from cache. I was wondering what happened suddenly. so I started looking at web page Headers - Status Code. It was 304 (Not Modified). Which means it was not refreshing data and returning results from Cache.

To solve the problem, I have added "rs:ClearSession=true" in the URL. This solved my issue.

http://servername/Reportserver?/SSRSRPT2RDL/Main&rs:Command=Render&rs:Format=PDF&rs:ClearSession=true&year=2018&source=Menu

Thanks

Tuesday, November 24, 2015

How to make ViewState secure and encrypted in ASP.NET

We can secure and encrypt ViewState by enabling these settings "EnableViewStateMAC" and "ViewStateEncryptionMode" in web.config:

<pages enableViewStateMac="true" ViewStateEncryptionMode="Always"/> 

 


Tuesday, September 2, 2014

Difference between Stored Procedure and Function in SQL Server

1. Functions must always return a value (either a scalar value or a table). Stored procedures may return a scalar value, a table value or nothing at all.

2. Functions can have only input parameters whereas Stored Procedures can have input/output parameters .

3. Functions can be called from Stored Procedure whereas Stored Procedures cannot be called from Function.

4. Stored Procedure allows SELECT as well as INSERT/UPDATE/DELETE statement whereas Function allows only SELECT statement.

5. Stored Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.

6. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.

7. The most important feature of stored procedures over function is to retention and reuse the execution plan while in case of function it will be compiled every time.

8. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.

9. Exception can be handled by try-catch block in a Stored Procedure whereas try-catch block cannot be used in a Function.

10. We can go for Transaction Management in Stored Procedure whereas we can't go in Function.

11. Stored procedures are called independently, using the EXEC command, while functions are called from within another SQL statement

Friday, August 8, 2014

A very simple example on System.Reflection in Asp.net

Today I will show you a very simple example on Reflection.

Follows the steps:

Step 1. Create a project with asp.net empty web application and name it "ReflectApp".

Step 2. Create a web form in it and paste following code and run it.

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, 
                            ByVal e As System.EventArgs) Handles Me.Load
        Dim currentAppName = System.Reflection.Assembly.Load("ReflectApp")

        For Each type As Type In currentAppName.GetTypes
            If type.Name = "Customer" Then
                Dim o As Object = Activator.CreateInstance(type)

                Dim mInfo As System.Reflection.MethodInfo = type.GetMethod("getName")

                If mInfo IsNot Nothing Then
                    Dim result As String = mInfo.Invoke(o, Nothing)

                    Response.Write(result)
                End If

                Exit For
            End If

        Next 
    End Sub
    Public Class Customer
        Private Property _Name As String

        Sub New()
            _Name = "John Miller"
        End Sub

        Public Function getName() As String
            Return _Name
        End Function

    End Class

End Class


Result will be: John Miller

You can debug and see how it works.

Thursday, August 7, 2014

Wednesday, August 6, 2014

Explain with example ISNULL, NULLIF and COALESCE in SQL Server


ISNULL : Replaces NULL with the specified replacement value.

NULLIF : Returns a null value if the two specified expressions are equal.

COALESCE : Returns the first non-null argument.(msdn: Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL).

Here are the examples and it's results:

SELECT ISNULL(null,1)
--Result: 1

SELECT NULLIF(1,1)
--Result: NULL

SELECT COALESCE(1,null,null,null)
--Result: 1

SELECT COALESCE(null,2,3,4)
--Result: 2

SELECT COALESCE(null,null,3,4)
--Result: 3

SELECT COALESCE(null,null,null,4)
--Result: 4

SELECT ISNULL(NULLIF(COALESCE(null,null,null,4),4),1)
--Result: 1


Tuesday, August 5, 2014

A very simple example on KnockoutJS in Asp.net

Today I will show you a very simple example on KnockoutJS in Asp.net

Please follows the steps:

Step 1: Create a project with Asp.net empty web application and add web form.

Step 2: Now, paste following code in "body" tag of your aspx page.
<body>
     
    <p>First name: <strong data-bind="text: firstName"></strong></p>
    <p>Last name: <strong data-bind="text: lastName"></strong></p>
    <p>
        First name:
            <input data-bind="value: firstName" />
    </p>
    <p>
        Last name:
            <input data-bind="value: lastName" />
    </p>
    <script
        src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.1.0.js">
    </script>
    <script>

        function AppViewModel() {
            this.firstName = ko.observable("John");
            this.lastName = ko.observable("Miller");
        }

        // Activates knockout.js
        ko.applyBindings(new AppViewModel());
    </script>
</body>


Now run your web form and try to change first name, it will automatically change the first name in the label as well.

Monday, August 4, 2014

How to bind dynamically HTML Ordered List in Asp.net using AngularJS?

Today I will show you a very simple example on binding HTML Ordered List dynamically in Asp.net using AngularJS.

Follows the steps:

Step 1: Create a project with asp.net empty web application and add web form in it.

Step 2: Now, paste following code in ".aspx" page
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div ng-app="" ng-controller="itemController">
            <ol>
                <li ng-repeat="item in items">{{ item }}
                </li>
            </ol>
        </div>

        <script>
            function itemController($scope) {
                $scope.items = [<%=items%>];
            }

        </script>
        <script 
            src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">

        </script>

    </form>
</body>
</html>


Step 3: Now, paste following code in ".aspx.vb" code behind page
Public Class WebForm1
    Inherits System.Web.UI.Page

    Public items As String = ""

    Protected Sub Page_Load(ByVal sender As Object,
                            ByVal e As System.EventArgs) Handles Me.Load

        If Not Page.IsPostBack Then
            'You can change this items dynamically '
            items = "'Orange', 'Apple', 'Banana', 'Grape', 'Watermelon'"
        End If

    End Sub

End Class


Result will be:

1.Orange
2.Apple
3.Banana
4.Grape
5.Watermelon


Friday, August 1, 2014

How to check or compare that two dates, not including time, are equal? in Asp.net

A very simple example of comparing two dates without including time as below:

One Way:
Dim date1 As Date = CDate("8/1/2014 11:00:00 PM")
Dim date2 As Date = CDate("8/1/2014 02:25:15 AM")

Dim result As Boolean = date1.Date.Equals(date2.Date)
'Result: True


Second Way:
Dim date1 As Date = CDate("8/1/2014 11:00:00 PM").ToShortDateString()
Dim date2 As Date = CDate("8/1/2014 02:25:15 AM").ToShortDateString()

Dim result As Boolean = Date.Equals(date1, date2)
'Result: True 


Thursday, July 31, 2014

How to display data on Asp.net web form without postback? using JSON, JQuery.ajax and WebMethod

To display data on web form without postback, we will use JSON, JQuery $.ajax, WebMethod and JavascriptSerializer. Sometime we need some data to be displayed when user wants it. Without user request, we don't want to show that data on aspx page. In this situation, we should give one button, so whenever user wants it, he will click and get the result.

How do we achieve this? just follows the steps:

Step 1: Create a project with Asp.net empty web application. and add "Default.aspx" page.

Step 2: In Default.aspx page, add following code.
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script> 
             function getRandomNumber() {
                 
                $.ajax({

                    url: "Default.aspx/getRandomNumber",
                    data: '',
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (mydata) {

                        var i = JSON.parse(mydata.d);
                        $("#lblRandomNumber").text(i);
                         
                    }
                });
            }  
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnRandomNumber" runat="server" 
                OnClientClick="javascript:getRandomNumber(); return false;"   
                Text="Get Random Number" />
            <asp:Label ID="lblRandomNumber" runat="server" ></asp:Label>
        </div>
    </form>
</body>
</html>


Step 3: Now, In Default.aspx.vb page, add following code.
Imports System.Web.Services
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services

Public Class _Default
    Inherits System.Web.UI.Page
     
    <WebMethod> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Shared Function getRandomNumber() As String

        Dim s As String = New Random().Next(100).ToString()
        Dim ser As New JavaScriptSerializer()
        Dim jsonString = ser.Serialize(s)
        Return jsonString
    End Function
     
End Class


Step 4: Now run it, and click on "get random number" button to get the random number without postback.



Wednesday, July 30, 2014

The thread '<No Name>' (0x12f8) has exited with code 0 (0x0). on await

Issue on Await: The thread '<No Name>' (0x12f8) has exited with code 0 (0x0). on await

This is thread deadlock issue. To avoid this issue, you should use ConfigureAwait(false) to make the runtime continue in a different thread.

await Task.WhenAll(aAsync, bAsync).ConfigureAwait(false);


The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Today I was working on Asp.net 4.5 website and I got following error:

The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

I have solved this issue by adding one line in web.config file:

    <compilation debug="true" targetFramework="4.5">
      <assemblies> 
        <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> 
      </assemblies>
    </compilation>


I got three of them, I have added all those assemblies into web.config like above and it works perfect.

How to convert JSON string to Javascript object?

You can convert JSON String to JavaScript Object Using JSON.parse method of JavaScript.

<script>
   //Json string
   var customer = '{"Name":"John","City":"NJ"}';
   var customers = '[{"Name":"John","City":"NJ"},{"Name":"Miller","City":"PA"}]';

   //Converting Json to Javascript Object
   var Customer = JSON.parse(customer);
   var Customers = JSON.parse(customers);

   //Result
   alert(Customer.Name);
   alert(Customers[1].Name);

</script>


Tuesday, July 29, 2014

How to connect Salesforce from Asp.net? Salesforce Integration in Asp.net

Today I will show you how to use new salesforce toolkit for .NET Application. Follows the steps:

Step 1. Create a project with C# ASP.NET 4.5 empty web application.

Step 2. Right click on this project and click on “Manage NuGet Packages”. Now search for “salesforce” and install “DeveloperForce.Force” NuGet package like this: see screen.



Step 3. After installing this package, add new webform in the project. Name it “Default.aspx”

Step 4. Before I show you complete code, you need five things from salesforce: “ConsumerKey, ConsumerSecret, username, password and security token”.

Note:A security token is an automatically generated key that you must add to the end of your password in order to log into Salesforce from an untrusted network. For example, if your password is mypassword, and your security token is XXXXXXXXXX, then you must enter mypasswordXXXXXXXXXX to log in.

Step 5. Paste following code in your “Default.aspx.cs” page.

    public partial class Default : System.Web.UI.Page
    {
        List<contact> Contacts;
        protected void Page_Load(object sender, EventArgs e)
        {
            Do().Wait();

            foreach (var item in Contacts)
            {
                Response.Write(item.LastName + ",");
            }
        }
        async Task Do()
        {
            //get credential values
            string consumerkey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
            string consumersecret = "XXXXXXXXXXXXXXXXX";
            string username = "XXXXXXXXXXX";
            string password = "mypasswordXXXXXXXXXX";

            //create auth client to retrieve token
            var auth = new AuthenticationClient();

            //get back URL and token
            await auth.UsernamePasswordAsync(consumerkey, 
                       consumersecret, username, password);

            var instanceUrl = auth.InstanceUrl;
            var accessToken = auth.AccessToken;
            var apiVersion = auth.ApiVersion;
            var client = new ForceClient(instanceUrl, accessToken, apiVersion);

            var contacts = await 
                client.QueryAsync<contact>("SELECT Id, LastName From Contact");

            Contacts = contacts.records;

        }
        public class Contact
        {
            public string Id { get; set; }
            public string LastName { get; set; }
        }

    }


Now, run your application and it works perfect :)

I hope this article will help you in connecting Salesforce from Asp.Net

Monday, July 28, 2014

What is the difference between IEnumerable and IEnumerator? ASP.Net

IEnumerable is an interface for all non-generic collections that can be enumerated. IEnumerable contains a single method, GetEnumerator, which returns an IEnumerator.

Syntax:
public interface IEnumerable
{
IEnumerator GetEnumerator();
}


IEnumerator provides the ability to iterate through the collection by exposing a Current property and MoveNext and Reset methods. Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Syntax:
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}


Friday, July 25, 2014

Partitions in Multidimensional Models (SSAS, SQL Server 2014)

In Analysis Services, a partition provides the physical storage of fact data loaded into a measure group. A single partition is created for each measure group automatically, but it is common to create additional partitions that further segment the data, resulting in more efficient processing and faster query performance.

Processing is more efficient because partitions can be processed independently and in parallel, on one or more servers. Queries run faster because each partition can be configured to have storage modes and aggregation optimizations that result in shorter response times. For example, choosing MOLAP storage for partitions containing newer data is typically faster than ROLAP. Likewise, if you partition by date, partitions containing newer data can have more optimizations than partitions containing older data that is accessed less frequently. Note that varying storage and aggregation design by partition will have a negative impact on future merge operations. Be sure to consider whether merging is an essential component of your partition management strategy before optimizing individual partitions.

Dimensions in Multidimensional Models (SSAS, SQL Server 2014)

A database dimension is a collection of related objects, called attributes, which can be used to provide information about fact data in one or more cubes. For example, typical attributes in a product dimension might be product name, product category, product line, product size, and product price. These objects are bound to one or more columns in one or more tables in a data source view. By default, these attributes are visible as attribute hierarchies and can be used to understand the fact data in a cube. Attributes can be organized into user-defined hierarchies that provide navigational paths to assist users when browsing the data in a cube.

Cubes contain all the dimensions on which users base their analyses of fact data. An instance of a database dimension in a cube is called a cube dimension and relates to one or more measure groups in the cube. A database dimension can be used multiple times in a cube. For example, a fact table can have multiple time-related facts, and a separate cube dimension can be defined to assist in analyzing each time-related fact. However, only one time-related database dimension needs to exist, which also means that only one time-related relational database table needs to exist to support multiple cube dimensions based on time.

Cubes in Multidimensional Models (SSAS, Sql Server 2014)

A cube is a multidimensional structure that contains information for analytical purposes; the main constituents of a cube are dimensions and measures. Dimensions define the structure of the cube that you use to slice and dice over, and measures provide aggregated numerical values of interest to the end user. As a logical structure, a cube allows a client application to retrieve values, of measures, as if they were contained in cells in the cube; cells are defined for every possible summarized value. A cell, in the cube, is defined by the intersection of dimension members and contains the aggregated values of the measures at that specific intersection.

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...