Sunday, November 4, 2018

Adding and removing an attribute from the entire group of array: ES6 Javascript

Adding and removing an attribute from the object array

I mostly like to elaborate things that I am writing about but sometimes answers need to be kept short and crisp, so I will get down to the answers right away.

1. Adding an attribute:

Entity:

export class Case {

  caseId: string;
  name: string;
  description: string;
}

Method to add attribute:

I need to add checked attributed to the array of Case:
const checkedCases = cases.map(obj => {
  return ({...obj, checked : false});
});

2. Removing the attribute

Entity:

export class CheckedCase {
  caseId: string;
  name: string;
  description: string;
  checked: boolean;
}

Method to remove attribute:

I need to add checked attributed to the array of Case:
const cases = checkedCases.map(obj => {
  delete obj.checked;
  return obj;
});

Unit testing D3 transitions

Hello everyone,

Today I am going to tell you about unit testing D3 transitions. Anyone working in Javascript technology would be very much aware with D3.js library. D3.js is a data driven javascript library for Dom manipulating, which comes with a large set of advanced features, enabling the quick calculation and rendering of very large data sets.


Recently I was working on creating charts using D3.js library and as the client demanded the chart needed to be fancied with some good animations.

First of all, creating transitions in D3 charts require a lot of skill for everything to fall in place and then writing unit tests for that is SOMETHING. (FYI, I am pretty new to D3.js library. Started working on them just a month back).

Chart code:

I am referencing to this d3 bar chart to write unit tests:

http://bl.ocks.org/enjalot/1429426


Unit tests:

function flushAllD3Transitions() {
    var now = performance.now;
    performance.now = function() { return Infinity; };
    d3.timerFlush();
    performance.now = now;
 }

Thank you for taking the time to read this. I hope this would have helped. 

P.S. If you want me to discuss any other topic, write to me in the comments below.

Monday, August 28, 2017

Unit Testing window.keyDown event Angular2 Karma Unit testing

Testing an event is one of the fascinating parts of unit testing. You are creating an event without even going to the screen.

In the series of Event Testing, I am going to tell you about testing a keyDown event on window.
I am not going into a detailed description of creating a component or writing a test file. Just explaining the methods:

In Test-component.ts

// Listen keyboard shortcuts@HostListener('window:keydown', ['$event'])
onKeyDown( event ) {
  // Esc button click  if (event.keyCode === 27 && event.code === 'Escape') {
    this.eventFired = true;
  }
}

In Test-component.spec.ts

it('should fire window keydown event', () => {
    const event: Event = new KeyboardEvent('keydown', {
      'code': 'Escape' //Code for the key
    });
    window.dispatchEvent(event);
    fixture.detectChanges();
    expect(component.eventFired).toBeTruthy();
  });


If you want any detailed description, please tell me in the comments below.


Unit testing an html input in Angular2 Karma Unit Testing

Recently I was working on creating a component, where I needed to unit test my input element.

I tried almost everything to test my input on text element but in vain. Though I have done it many times before with a form control attached to it and it was easy. But this was new...

So just to save you guys some time, below is the code snippet for the same.

test-component.ts:

@Component({
  selector: 'test-component',
  template: '

'
})
class TestComponent {
  name: string;
}

test-component.spec.ts:
Just writing the test case assuming that you know the how to write the test cases in Karma.

inputElement = fixture.debugElement.query(By.css('input')).nativeElement;

it('should set input value programatically', () => {
 
  inputElement.dispatchEvent(new Event('focus'));
  inputElement.value = 'Pratibha';
  inputElement.dispatchEvent(new Event('input'));

  fixture.detectChanges();
  expect(componennt.name).toEqual('Pratibha');
});






Tuesday, August 10, 2010

Calling Server Side Function from javascript


Hello developers,


Many times what happens is that we are using HTML controls in an aspx page and we want to have database interaction to populate some control,
or when we are not willing to use complex javascript functions for string manipulation or any other stuff,
Then we just eagerly want to use the server side functions or database connectivity without postback.


Best thing that you can do that time is write the entire code in Server side function and then call that function from  client side javascript.


In this blog, I am going to tell you exactly this thing:



At codebehind file, create your server side method and write following two lines before that:
[System.Web.Services.WebMethod]
 [System.Web.Script.Services.ScriptMethod()]
This will make your server side function visible to javascript.

Note: Do remember to set EnablePageMethods property od ScriptManager to true.


A simple Example:

At codebehind file:
[System.Web.Services.WebMethod]
 [System.Web.Script.Services.ScriptMethod()]
    public static string SayHello()
    {
string strData = “Hello”;      
return strData;
    }

From Javascript: Call your server side method from your javascript nethod by using 
PageMethods. OnSucceeded and OnFailed are two callback functions which are always passed as parameters.

function  AlertingHello(){
PageMethods.SayHello(OnSucceeded, OnFailed);

}

 If your server side method will execute successfully, you will get the result in the OnSucceeded function:
function OnSucceeded(result, userContext, methodName) {
if(methodname==”SayHello”)
{
 alert(result);//you will get "Hello" in result.
}
}



If your server side method will not execute successfully, you will get the result in the OnFailed function. You can write nay code in the onFailed method to tell the user that the error occurred.




function OnFailed(error, userContext, methodName) {
if(methodname==”SayHello”)
{
 alert("Some Error Occurred");
}
}


A complex Example:

Imagine there are are few textfields that you want to fill on the selection of a dropdown or select control of html:

Here the scenario is We'll select the name of an employee from a dropdown list and 
and accordingly Fill his details in textfields.

At OnChange event of dropdown, you can call the javascript function:

In Client side page:

  function FillDataInControls() {
                var dropDown = document.getElementById('<%=ddlName.ClientID%>');
                var name = dropDown.options[dropDown.selectedIndex].value;
                PageMethods.FillControls(name, OnSucceeded, OnFailed);
            }

At code behind file:

[System.Web.Services.WebMethod]
 [System.Web.Script.Services.ScriptMethod()]


    public static string FillControls(string name)
    {
        DataSet dsDetails = new DataSet();
        string strData = string.Empty;
        try
        {
            if (name != "")
            {
                GetDetailsBL objGetDetailsBL = new GetDetailsBL();
                dsDetails = objAddCoupanBL.GetddlCouponCode(name);

                if (dsDetails.Tables[0].Rows.Count > 0)
                {
                    strData = name;
                    employeeId = int.Parse(dsDetails.Tables[0].Rows[0]["EmployeeId "].ToString());
                    dob = dsDetails.Tables[0].Rows[0]["dob"].ToString();
                    strData = strData + "^" + dob;
                    address= dsDetails.Tables[0].Rows[0]["address"].ToString();
                    strData = strData + "^" + address;
                    dateofjoin= dsDetails.Tables[0].Rows[0]["dateofjoining"].ToString();
                    strData = strData + "^" + dateofjoin;
                    position= dsDetails.Tables[0].Rows[0]["position"].ToString();
                    strData = strData + "^" + position;
                    manager= dsDetails.Tables[0].Rows[0]["managerId"].ToString();
                    strData = strData + "^" + manager;
                    salary= dsDetails.Tables[0].Rows[0]["salary"].ToString();
                    strData = strData + "^" + salary;
                }
            }
        }
        catch { }
        return strData;
    }

In Client side page:

create the callback function onSucceeded like this: I am assuming that all the text fields are html controls.
If the text fields are server side controls:
we can use 
document.getElementById('<%=txtEmpName.ClientID%>').value
instead of
document.getElementById('txtEmpName').value

function OnSucceeded(result, userContext, methodName) {
if (methodName == "FillControls") {
   if(result!="")
   {
    var data = result.split('^');
document.getElementById('txtEmpName').value=data[0];
document.getElementById('txtEmpId').value=data[1];
document.getElementById('txtEmpDob').value=data[2];
document.getElementById('txtEmpAddress').value=data[3];
document.getElementById('txtEmpDateOfJoin').value=data[4];
document.getElementById('txtEmpPosition').value=data[5];
document.getElementById('txtEmpManager').value=data[6];
document.getElementById('txtEmpSalary').value=data[7];
     }


  }
}

That's it about "Calling Server Side Function from Javascript". 
I hope it helps.
:)











Tuesday, August 3, 2010

Disable/Enable Javascript in Internet Explorer programmatically


Hello everybody,
Currently I was involved in a project where I had to disable Javascript from registry.
After a lot of searching and googling I came across these links:


But for me, I had to do it programmatically so I started writing the code and after some issues and problems, It worked. :).
I came across number of similar questions on other forums. Owing to my big heart, I decided to blog it and here I am:
I am not going in much detail as starting from create a Website or web Application or windows appluication and blah blah blah!
Assuming you are all smart programmers, I would start with creating a button and working on its click.
In the design page: 

 Just create a button on the page with text as Disable Javascript and name as 

btnDisableJavascript

In the code page:

Namespace: using Microsoft.Win32;

   //Click of btnDisableJavascript
    protected void btnDisableJavascript_Click(object sender, EventArgs e)
    {
         bool disable = false;

        if (btnDisableJavascript.Text == "Disable Javascript")
        {
            disable = true;
            btnDisableJavascript.Text = "Enable Javascript";
        }
        else
        {
            disable = true;
            btnDisableJavascript.Text = "Disable Javascript";
        }
        EnableDisableJavaScript(disable);
    }

    //Disable/Enable Javascript from code(Registry):
    public static void EnableDisableJavaScript(bool enable)
    {
         //get the registry key for Zone 3(Internet Zone)
        RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3", true);
        //get the registry key for Zone 1(Local Intranet Zone)
        RegistryKey keyLocalFiles = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1", true);
        //get the registry key for Zone 1(My Computer)
        RegistryKey keyMyComputer = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\0", true);
        if (value == true)
        {
            try
            {
                if (key != null)
                {
                    //1400 is the DWORD for Scripting: Active scripting
                    //setting of "3" prohibits the specific action i.e. disable for this case
                    key.SetValue("1400", "3", RegistryValueKind.DWord);
                    keyLocalFiles.SetValue("1400", "3", RegistryValueKind.DWord);
                    keyMyComputer.SetValue("1400", "3", RegistryValueKind.DWord);
                }
                else
                {
                    key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3");
                    keyLocalFiles = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1");
                    keyMyComputer = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\0", true);
                    //1400 is the DWORD for Scripting: Active scripting
                    //setting of "3" prohibits the specific action i.e. disable for this case
                    key.SetValue("1400", "3", RegistryValueKind.DWord);
                    keyLocalFiles.SetValue("1400", "3", RegistryValueKind.DWord);
                    keyMyComputer.SetValue("1400", "3", RegistryValueKind.DWord);
                }

            }
            catch (Exception ex)
            {

            }
        }
        else
        {
            try
            {
                if (key != null)
                {
                    //setting of "0" sets a specific action as permitted i.e. enable for this case
                    key.SetValue("1400", "0", RegistryValueKind.DWord);
                    keyLocalFiles.SetValue("1400", "0", RegistryValueKind.DWord);
                    keyMyComputer.SetValue("1400", "0", RegistryValueKind.DWord);
                }
                else
                {
                    key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3");
                    keyLocalFiles = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1");
                    keyMyComputer = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\0");
                    //1400 is the DWORD for Scripting: Active scripting
                    //setting of "0" sets a specific action as permitted i.e. enable for this case
                    key.SetValue("1400", "0", RegistryValueKind.DWord);
                    keyLocalFiles.SetValue("1400", "0", RegistryValueKind.DWord);
                    keyMyComputer.SetValue("1400", "0", RegistryValueKind.DWord);
                }

            }
            catch (Exception ex)
            {

            }
        }
    }

When you'll run, the disable javascript button is displayed as follows:

Click this button, after processing is complete, go to Tools>Internet Options< Active Scripting

you can see the checkbox for Disable is checked as below

and the Text of the button is changed to Enable Javascript:
Now if you run any website involving javascript, you can very easily figure out that javascript is disable:

For example try and run www.msn.com; you'll not be able to see any thing over ther as the javascript is disabled.

Click this button now and after processing is complete, Tools>Internet Options< Active Scripting

you can see the checkboxes for you can see the checkbox for Enable is checked as below:





Now after scripting is enabled try and run www.msn.com; you'll it will run as it used to.


And thats a yippi and happy case.
As our target is achieved.

Thats all for "Disable/Enable Javascript in Internet Explorer programmatically".

Catch you all some other day with some other knowledge stuff.