Monday, January 16, 2017

Namespace and extending twitter bootstrap


Using customized bootstrap styles can sometimes conflict with other bootstrap styles that are not customized, for example this could happen if you have a frame and you are loading a web component inside of it inside a page.

Possible solution to avoid conflicts is to namespace twitter bootstrap

Lets take example html with bootstrap styling

<html>
<head>
    <title>My Twitter Bootstrap example</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
    <ul class="nav nav-pills" role="tablist">
        <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a></li>
        <li role="presentation"><a href="#">Profile</a></li>
        <li role="presentation"><a href="#">Messages <span class="badge">3</span></a></li>
    </ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

To namespace bootstrap styles:
Create a new less file, and paste the below inside. "mybt" below is the custom namespace i am using

.mybt {
    @import "bootstrap-3.3.7/less/bootstrap";
}

After that compile this less file
lessc mybt.less mybt.css

And now after referencing mybt.css the html would use mybt and the bootstrap styles like below

<html>
<head>
    <title>My Twitter Bootstrap example</title>
    <link rel="stylesheet" href="mybt.css">
</head>
<body>
    <ul class="mybt nav nav-pills" role="tablist">
        <li role="presentation" class="mybt active"><a href="#">Home <span class="mybt badge">42</span></a></li>
        <li role="presentation" class="mybt"><a href="#">Profile</a></li>
        <li role="presentation" class="mybt"><a href="#">Messages <span class="mybt badge">3</span></a></li>
    </ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

Another option is to extend bootstrap styles
to extend it, create new less file with below:

@import "bootstrap-3.3.7/less/bootstrap";

.my-nav:extend(.nav) {}
.my-nav-pills:extend(.nav-pills) {}
.my-badge:extend(.badge) {}

Extending will work if you have only few styles that you are using.

Sunday, January 8, 2017

Setup Blocked By Group Policy

I was trying to setup my printer, cannon MG3650 on my computer, everything was going well, setup has finished, but i wasn't able to print.
I opened printers, to find the status of the printer as following "Setup Blocked By Group Policy"
Searching online i found couple of posts to change the group policy and how to check the resultant policy.
I checked the group policy setting by doing the below
Start > Run, type in gpedit.msc and press OK. Go to Computer Configuration > Administrative templates > System > Device Installation > Device Installation Restrictions
Made sure that all was not configured.
I then checked the resultant policy
Start > Run, type in rsop.msc and there the device restriction was set as enabled.
I searched on how to change this policy, couldn't find a place to change it.

Then i looked into the registry. by doing Start > Run, type in regedit and press Ok. I found the below key:

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\DeviceInstall\Restrictions

And i found a key inside called DenyUnspecified

I removed this key, then checked the resultant policy, the restriction wasn't enabled. Repeated the printer setup again, and this time it finished successfully and it worked fine after. 

Friday, December 16, 2016

Custom cast support for objects


We are working with Hashtables a lot in a project, where we need to convert objects into hashtable and from hashtables

A way to do this is by adding custom casting in the class to the class type, and to add a method to convert to hashtable.

Example

   public class MyClass
    {
        public string Name;
        public int Id;
        public string Description;

        public static explicit operator MyClass(Hashtable hashtable)
        {
            MyClass mt = new MyClass();
            mt.Description = hashtable["Description"].ToString();
            mt.Id = int.Parse(hashtable["Id"].ToString());
            mt.Name = hashtable["Name"].ToString();
            return mt;
        }

        public Hashtable ToHashtable()
        {
            var hashtable = new Hashtable();
            hashtable["Name"] = "name";
            hashtable["Id"] = 1;
            hashtable["Description"] = "description";
            return hashtable;
        }
    }
Then simply we can do something like:
Hashtable hashtable = myClass.ToHashtable();

And 
MyClass casted = (MyClass) hashtable;
Example usage:
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass
            {
                Description = "description",
                Id = 1,
                Name = "name"
            };

            Hashtable hashtable = myClass.ToHashtable();
            Console.WriteLine("Hashtable: ");
            Console.WriteLine(hashtable["Name"]);
            Console.WriteLine(hashtable["Id"]);
            Console.WriteLine(hashtable["Description"]);


            MyClass casted = (MyClass) hashtable;
            Console.WriteLine("MyClass: ");
            Console.WriteLine(casted.Id);
            Console.WriteLine(casted.Description);
            Console.WriteLine(casted.Name);

            Console.ReadKey();
        }

Wednesday, December 14, 2016

Error CA2000 call System.IDisposable.Dispose on object

My code looked like


this.client.Setup(mock => mock.PostAsync(It.IsAny<IEnumerable<ids>>())).Returns(Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK)));

and i was getting the below style cop error

Severity Code Description Project File Line Suppression State
Error CA2000 In method 'MyMethod()', call System.IDisposable.Dispose on object 'new HttpResponseMessage(HttpStatusCode.OK)' before all references to it are out of scope. Catalog.Common.UnitTests code.cs 72 Active

To overcome this, if it is in single method, you can suppress the error

[SuppressMessage("Microsoft.Reliability",
                 "CA2000:DisposeObjectsBeforeLosingScope",
                 Justification = "Your reasons go here")]
OR you can change the code to be like below

this.client.Setup(mock => mock.PostAsync(It.IsAny<IEnumerable<ids>>())).Returns(Task.Run(() => { return new HttpResponseMessage(System.Net.HttpStatusCode.OK); }));

Wednesday, March 11, 2015

Recovering partition after initializing by mistake

I recently re installed windows, i have 2 drives, i have removed the second drive to keep the data safe.
After the installation i have connected my hard drive. I didn't find the drive appearing in file explorer. When i opened Computer Management-> Disk Management, i received message saying that the drive is not initialized, so i followed the steps to initialize it, thinking that this will restore the drive and the data, then i found that the drive now has the state of un-allocated and the next available options is to create volumes, then i realized that i may have destroyed my data.
Looking online i found some forums talking about something similar and that MiniTool Partition wizard have recovery wizard that can recover the drive
http://www.sevenforums.com/hardware-devices/288692-disk-1-unknown-not-initialized-unallocated.html

I gave it a try, downloaded the free tool from http://www.partitionwizard.com/download.html, then selected the drive, started the recovery wizard, did the quick scan, and voila, the partition was recovered. That was really great tool that saved my data.

Sunday, January 18, 2015

Remote desktop connection: Authentication error has occurred (Code: 0x80004005)

Usually i connect to my other machine without any problems, one time suddenly i was receiving this error:

Authentication error has occurred (Code: 0x80004005)

And here is my experience with it, searching for it found this post saying that it could because of third party software or antivirus. Then i remembered that sometimes when i had fiddler open on my machine, i get authentication errors from outlook and some other clients that are unable to connect with the server on secure connections, i figured out that this could be the reason, that i have fiddler open in my machine and it is blocking the authentication.

So i needed to shut down fiddler on my remote machine, i remember that PsTools allows executing commands on remote machine, Then i found this article on steps to run PsKill to kill process on remote machine.

All i needed to do is:
- Download PsTools, then extract it
- Start command prompt in elevated mode (run as administrator)
- Go to PsTools extracted folder on run the command

pskill.exe \\MachineName -u username -p password Fiddler

Should take some time and come back with

Process Fiddler killed on MachineName

Trying to remote connect to my machine after that, worked as usual.

Wednesday, December 17, 2014

Windows 8 apps opening problem

On my work PC i had this issue, domain account on windows 8, and whenever i tried to open any of windows 8 apps, it is opened and disappears and the window is not displayed.
When i searched i found lots of articles taking about windows apps issues, but all didn't help. I found helpful articles when i searched with the error i found in event viewer like:


Activation of app windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel failed with error: This app does not support the contract specified or is not installed. See the Microsoft-Windows-TWinUI/Operational log for additional information.

I found the solution in couple of articles

I can't open any Windows 8 apps including PC Settings and Store
Fix Windows 8.1 Cannot Launch “PC Settings” or “Store” Problem

Running the below commands solved the problem

powershell -ExecutionPolicy Unrestricted Add-AppxPackage -DisableDevelopmentMode -Register $Env:SystemRoot\camera\AppxManifest.xml
powershell -ExecutionPolicy Unrestricted Add-AppxPackage -DisableDevelopmentMode -Register $Env:SystemRoot\FileManager\AppxManifest.xml
powershell -ExecutionPolicy Unrestricted Add-AppxPackage -DisableDevelopmentMode -Register $Env:SystemRoot\ImmersiveControlPanel\AppxManifest.xml

Monday, October 20, 2014

Enabling remote desktop on remote computer

I went home and forgot to enable remote desktop on my PC at my office, luckily i found couple of articles that is talking about enabling remote desktop remotely.

I followed the steps from  here and did a restart for the remote machine, but it didn't work, then i figured that since i did it through registry, firewall rules wasn't updated to allow it, while if i enabled remote desktop connections through the UI, it is updated automatically.

I found another article that has the same steps plus updating the firewall to enable remote desktop connections with a command line that is executed remotely. Another article for opening the firewall for remote desktop connections from command line.

The only thing that i have done extra is that i started the elevated command prompt for "psexec", the normal one didn't do the job.

Brief of the steps:
1- From the registry, connect to the remote computer
2- Change the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\fDenyTSConnections from 1 to 0
3- Restart the remote machine by shutdown -m \\MachineName -r
4- Update the firewall rules on the remote machine by downloading psexec and running the below from elevated command prompt
psexec \\remote_machine_name cmd
Then after it connects
netsh advfirewall firewall set rule group=”remote desktop” new enable=Yes

Thursday, June 26, 2014

.NET C#: Running command line in CMD and waiting for it to finish

I had a script that i should call with command line interface, then other tasks that should be done after that.
I used the Process and ProcessStartInfo as below, but the problem i had is that the script was taking some time, and the program execution was failing after that since the script is not finished yet.

            using (Process process = new Process())
            {
                var startInfo = new ProcessStartInfo("cmd")
                {
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    WindowStyle = ProcessWindowStyle.Normal,
                    UseShellExecute = false,
                    CreateNoWindow = false
                };

                process.StartInfo = startInfo;
                process.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
                process.Start();
                process.StandardInput.Write("script"+ process.StandardInput.NewLine);
                process.Close();
            }

I wanted to make sure that the program execution waits till the script finishes.So instead of using Close method, i added WaitForExit, and i am manually sending exit command to the command line after the script finishes, like below

            using (Process process = new Process())
            {
                var startInfo = new ProcessStartInfo("cmd")
                {
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    WindowStyle = ProcessWindowStyle.Normal,
                    UseShellExecute = false,
                    CreateNoWindow = false
                };

                process.StartInfo = startInfo;
                process.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
                process.Start();
                process.StandardInput.Write("script"+ process.StandardInput.NewLine);
                process.StandardInput.Write("exit" + process.StandardInput.NewLine);
                process.WaitForExit();
            }

This worked for me and the program execution waited till the script finishes.

Wednesday, June 18, 2014

Clicking problems with IE and Selenium

We were facing couple of problems with selenium tests running on IE, when running the tests locally, we don't have these issues. After adding more logs to the code, i found that sometimes it is failing after sending the click event in different steps. 
Looking online for similar issue, i found that there are clicking issues with IE, as sometimes the element being clicked on will receive the focus, but the click will not be processed by the element.
https://code.google.com/p/selenium/wiki/InternetExplorerDriver#Browser_Focus

To workaround this, i am setting the focus manually to the browser using the below line of code

Driver.SwitchTo().Window(Driver.CurrentWindowHandle);