adsense

Monday, December 14, 2020

Convert .net object into a JSON string

We can use JsonWriter to return a JSON representation of any .Net object as displayed below.


public class Person

    {

        public Int Id   {set ; get;}

        public String Name{set ; get;}

       public List<PhoneNumbers> Contacts{set ; get;}

         public String ToJSONRepresentation()

        {

            StringBuilder stringBuilder = new StringBuilder();

            JsonWriter jsonWriter = new JsonTextWriter(new StringWriter(stringBuilder));


            jsonWriter.Formatting = Formatting.Indented;

            jsonWriter.WriteStartObject();

            jsonWriter.WritePropertyName("id");

            jsonWriter.WriteValue(this.Id);

            jsonWriter.WritePropertyName("name");

            jsonWriter.WriteValue(this.Name);


            jsonWriter.WritePropertyName("phonenumbers");

            jsonWriter.WriteStartArray();


            int i=0;


            for (i = 0; i < Contacts.Count; i++)

            {

                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName("homePhone");

                jsonWriter.WriteValue(addresses[i].homePhone);

                jsonWriter.WritePropertyName("workPhone");

                jsonWriter.WriteValue(addresses[i].workPhone);

                jsonWriter.WritePropertyName("mobilePhone");

                jsonWriter.WriteValue(addresses[i].mobilePhone);

                jsonWriter.WriteEndObject();

            }

            jsonWriter.WriteEndArray();

            jsonWriter.WriteEndObject();

            return stringBuilder.ToString();

        }

      }

}


Cheers

Samitha

Friday, November 20, 2020

SQL get specific element Count in XML

 Consider this XML


Suppose you want to get count of student ids. You can use SQL to get the count as follows.

declare @xml XML;

set @xml ='<Students>

    <Student>

        <Id>001</Id>

        <Fname>Leesa</Fname>

        <Sname>Humpry</Sname>

    </Student>

    <Student>

        <Id>002</Id>

        <Fname>Clara</FName>

        <Sname>Margrette</Sname>

    </Student>

  </Students>';

select @xml.value('count(/Students/Student/Id)', 'INT') AS 'Count'

Cheers

Samitha

Sunday, November 8, 2020

sql server remove duplicates from query

You can use SQL row_number() function to remove duplicate rows from a query.

Create table Employees (fname varchar(100), lname varchar(100))

Insert into Employees Values 
               ('Tim', 'May')
             , ('Clara', 'Magrette') 
             , ('Clara', 'Magrette')
             , ('Jeff', 'Lawry') 
             , ('Brian', 'Adams')
             , ('Paul', 'Oliver')

As you can see there are duplicate records in the Employees table,

Select * from(
SELECT fname 
       ,lname 
       ,row_number() over (partition by fname , lname order by fname , lname ) as rownum 
FROM Employees 
) result
where rownum= 1 -- selects DISTINCT Employees only

Cheers,
Samitha

Wednesday, October 28, 2020

Remove all table rows except first

You can use jQery to easily remove rows from a given table.

//using jQuery find

$(function() {
   $("#tableId").find("tr:gt(0)").remove();
});
//using empty
$(function() {
  $("#tableId > tbody").empty();
});
The second method is more efficient than the first approach.
Regards,
Samitha

Saturday, October 17, 2020

.Net get plain text from HTML

There can be situations where you want to get plain text from HTML content.  We can use Regex and HttpUtility.HtmlDecode as the easiest way to get plain text shown below.

String plainText =HttpUtility.HtmlDecode( Regex.Replace(HtmlString, "<(.|\n)*?>", "") );


Cheers,

Samitha

Thursday, October 1, 2020

Role does not have permission for this action in QNA Maker

 When you are working with Azure QNA Maker you might get the message "role does not have permission for this action in QNA Maker"

Once you have finished creating  QNA,  the entire page (not the  Refresh Button on the QnAMaker.ai/Create page)  needs to be refreshed and the above message will be disappeared.


Cheers

Samitha

Tuesday, September 15, 2020

using iif to check null

IIf is a function which evaluates all its arguments, Vb net has if operator which works similar to the short circuit  if operator.

 e.g.

varName =   If(objName Is Nothing, "", objName.ToString())

Monday, August 31, 2020

kendo MultiColumnComboBox change selected value

 

If you are working with the Kendo MultiColumnComboBox  you might observe that even if try to reset the selected value you can n't do that.

Even if you try to set value to blank that will not be updated. The way to achieve this is shown as below.


var ddlOptions = $("#ddlOptions").data("kendoMultiColumnComboBox");

ddlOptions.value("");

ddlOptions.trigger("change");


Cheers

Samitha

Tuesday, July 21, 2020

change height/width of toast message

You can use following css to change height/width of the toast message/

#toast-container-id > div {
   width: 250px;
   height: 250px;
}

cheers
Samitha

 

Saturday, May 30, 2020

ASP.NET MVC using data attributes in html helper classes

You can use data  attributes in html helper classes as displayed below.

@Html.TextBoxFor(model=> model.PostCode, new { data_validate = "true" })

Cheers,
Samitha

Sunday, May 24, 2020

communicating with an IFRAME

I wanted to automatically resize the content of an iframe for one of my projects.  I tried several solutions and done several  google searches to find a working solution for my issue. I got the initiative  from here and it helped me to achieve what I needed.

 Parent page

<head>

<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous">
</script>

<script type="text/javascript">
         // addEventListener support for IE8
            function bindEvent(element, eventName, eventHandler) {
                if (element.addEventListener) {
                    element.addEventListener(eventName, eventHandler, false);
                } else if (element.attachEvent) {
                    element.attachEvent('on' + eventName, eventHandler);
                }
            }
         
            // Listen to message from child window
            bindEvent(window, 'message', function (e) {
         
                var height = parseInt(e.data.height);
         
                if (!isNaN(height)) {
$('iframe[id="frame1"]').css('height', height + 'px');
                }
            });
</script>

<head>

<body>

<iframe id="ConnXCareersFrame1" src="https://abcd.com/index.html"  width="1000" frameborder="0" scrolling="no"&gt;&lt;/iframe>

<body>;

Child page

<head>

<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous">
</script>

<script type="text/javascript">
var height =$('body,html').outerHeight() ;

 window.parent.postMessage({
                    'height': height
                }, "*");

</script>


<head>

<body>

<div>
 <!--content here -->
</div>

<body>;

Cheers,
Samitha

Sunday, May 17, 2020

docker: “build” requires 1 argument

When you  are trying to build a docker image from the docker website, you might encounter following error.

docker build -t dockerTest/redis
docker: "build" requires 1 argument. See 'docker build --help'

This error occurs when you use the Dockerfile in the local directory This error can be avoided by adding a dot in the end as displayed below.

docker build -t dockerTest/redis .

Note that if you using docker 1.5 you can specify a Dockerfile in another place.

docker build -f, --file=""

Cheers,
Samitha

Thursday, May 7, 2020

Powershell Install-Module error


The Install-Module command is used to  install or update modules. When you are trying to execute Install-Module  you might encounter following error 

Install-Module: The term Install-Module is not recognized as the name of cmdlet, function, script file or operable program

The cause of this errors is your PowerShell is not upto date.  To execute this command major virsion of PwerShel should be greater than 5.


This issue can be resolved by installing  Windows Management Framework 5.1  

Cheers,
Samitha


Friday, May 1, 2020

Azure Functions Core Tools

If you are going to work with Azure Functions , Azure Functions Core Tools is a must have tool set to be installed.

to install with NPM

npm i -g azure-functions-core-tools@3 --unsafe-perm true


Read more information here.

Cheers,
Samitha


Saturday, April 18, 2020

Unable to download the list of available providers Powershell

When you try to install a program you might encounter following error

WARNING: MSG:UnableToDownload «https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409» «»

WARNING: Unable to download the list of available providers. Check your internet connection.

WARNING: Unable to download from URI 'https://go.microsoft.com/fwlink/?LinkID=627338&clcid=0x409' to ''.

Install-PackageProvider : No match was found for the specified search criteria for the provider 'NuGet'. The package provider requires 'PackageManagement' and 'Provider' tags. Please check if the specified package has the tags.

At line:1 char:1

+ Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.2  01 -Force

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (Microsoft.Power...PackageProvider:InstallPackageProvider) [Install-PackageProvider], Exception

    + FullyQualifiedErrorId : NoMatchFoundForProvider,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackageProvider

Trying the following steps will resolve this issue.

  • Open Powershell (As Admin)
  •  execute following command in powershell prompt
          [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
  • Try running the again!
       Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force


Cheers,
Samitha

Friday, April 10, 2020

msbuild fails to run

When you are trying to publish a web through command line  you might encounter following error

MSBUILD : error MSB1009: Project file does not exist

Fix this by adding msbuild.exe to environement variables


The path is located in the Visual Studio Installed directory.

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin

Samitha

Saturday, March 28, 2020

fetch results of a stored procedure

If you want to get results of a executed  stored procedure, there few ways you can achieve the goal.

1. using openrowset

SELECT * INTO #TempTable FROM OPENROWSET('SQLNCLI', 'Server=(local)\SQL2008;Trusted_Connection=yes;',
     'EXEC getOrderHistory')

SELECT * FROM #TempTable

2. using temporary table

INSERT INTO #TempTable
Exec getOrderHistory 'Params'

Regards,
Samitha

Thursday, March 12, 2020

Handling Bootstrap switch checked event

If you are using Bootstrap switch, use the following jquery to track the Bootstrap switch checked event


$('.switcher').on('switchChange.bootstrapSwitch', function (event, state) {
   //more code here
 });

Regards,
Samitha

Sunday, March 1, 2020

Error: ENOENT: no such file or directory

When you are working with node js packages you might encounter  Error: ENOENT: no such file or directory, scandir '**/node_modules/node-sass/vendor' for one or some of the packages you are using.

execute following command for all the packages that gave ENOENT  error and it will fix the issue

cheers
Samitha


Tuesday, February 18, 2020

CSS select label

If we want to apply style for elements rendered  label for   use the following CSS

label[for=ID_of_the_Label]
{
    
}


Cheers,
Samitha

Sunday, February 2, 2020

'gulp' is not recognized as an internal or external command,

I have installed npm and working for the past few months without an issue. I was trying to execute a gulp task and came across the issue of gulp not working. The visual studio output displayed as follows

 'gulp' is not recognized as an internal or external command.

I fixed this issue by re installing gulp using  the following command

npm install -g gulp


Cheers,
Saamitha

Wednesday, January 1, 2020

FluentValidation validating bool

When validating boolean properties  using FluentValidation, use .NotNull() instead of .NotEmpty()

The reason behind this is NotEmpty() will consider only true as valid property whereas NotNull() will consider both true and false as valid properties.

Cheers
Samitha