Dynamic ItemsSource in WPF

I was just playing around and I had an idea of binding data dyanmically to a telerik gridview. I have some 25 tables in a database and I give the option to select the table to the user and the gridview should display data from that table.

I used some help from stackoverflow.

  <telerik:RadGridView ItemsSource="{Binding TableData}" AutoGenerateColumns="True"/>

and a extension method for data reader

        public static IEnumerable<dynamic> AsEnumerable(this System.Data.IDataReader source)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            var columns = Enumerable.Range(0, source.FieldCount).Select(source.GetName).ToList();

            while (source.Read())
            {
                
                dynamic dRow = new ExpandoObject();
                foreach (var column in columns)
                {
                    ((IDictionary<string, object>)dRow).Add(column, source[column]);
                }
                yield return dRow;
            }
        }

and bind it to the ObservableCollection. That’s it.

Angularjs – Modules

This blog is basically for me to look back and understand about the angularjs modules.

A module is a collection of services, directives, filters and configuration information.

The angular.module is a global place for creating, registering and retrieving angular modules. “angular.module” is the function used to retrieve or create angularjs modules. If passed two or more parameters a new module is created and if passed a single parameter it will return the module with the provided name.

   //Create a new module
   var anyModule = angular.module('anyModule', []);

   //register a new service
   anyModule.value('anyAppName', 'name');

   //configure existing services inside config method
   anyModule.config('$locationProvider', '$resourceProvider', function($locationProvider, $resourceProvider){
  //configure providers here
});

  //one can create an injector and load your modules too
  var injector = angular.injector(['ng', 'anyModule']);

‘angular.module’ takes 3 parameters ‘name’, ‘requires’, ‘config’.
‘name’ -> module to create or retrieve
‘requires’ -> required modules for this module to run (dependencies)
‘config’ -> any configuration for the module (Use this to register work which needs to be performed on module loading).

By default, it uses provider service to create a new instance of the service.
it uses provider service to instantiate $provider.provider(), $provider.factory(), $provider.service(), $provide.value, $provice.constant()
and registers $animation, $filterProvider, $controllerProvider, $compileProvider with the newly created module.

Getting Started with ASP.NET vNext

Article posted on Asp.Net vNext Overview

Getting Started with ASP.NET vNext
By
Mike Wasson |

The next version of ASP.NET (“ASP.NET vNext”) has been re-designed from the ground up. The goal is to create a lean and composable .NET stack for building modern cloud-based apps.

Here are some of the features of ASP.NET vNext:

  • vNext includes new cloud-optimized versions of MVC, Web API, Web Pages, SignalR, and Entity Framework.
  • MVC, Web API, and Web Pages will be merged into one framework, called MVC 6. The new framework removes a lot of overlap between the existing MVC and Web API frameworks. It uses a common set of abstractions for routing, action selection, filters, model binding, and so on. You can use the framework to create both UI (HTML) and web APIs.
  • ASP.NET vNext apps can use a cloud-optimized subset of .NET vNext. This subset is factored for server and web workloads, has a smaller footprint than the full .NET vNext, and supports side-by-side deployment.
  • MVC 6 has no dependency on System.Web. The result is a leaner framework, with faster startup time and lower memory consumption.
  • vNext will support true side-by-side deployment. If your app uses the cloud-optimized subset of .NET vNext, you can bin deploy all of your dependencies, including the .NET vNext (cloud optimized) packages. That means you can update your app without affecting other applications on the same server.
  • vNext is host agnostic. You can host your app in IIS, or self-host in a custom process. (Web API 2 and SignalR 2 already support self-hosting; ASP.NET vNext brings this same capability to MVC.)
  • Dependency injection is built into the framework. Use your preferred IoC container to register dependencies.
  • vNext uses the Rosyln compiler to compile code dynamically. You will be able to edit a code file, refresh the browser, and see the changes without rebuilding the project.
  • vNext is open source and cross platform.

In order to accomplish these goals, ASP.NET vNext contains breaking changes. The current frameworks (Web Forms 5, MVC 5, Web API 2, Web Pages 3, SignalR 2, and Entity Framework 6) will continue to ship in Visual Studio, and will be fully supported in .NET vNext.

This overview is designed to get you started with ASP.NET vNext. Because vNext is still an early preview, I won’t walk through creating an entire real-world application. Instead, I want to highlight some of the features and show enough code to get you started.

The overview assumes you are familiar with either MVC 5 or Web API 2. If not, here is some terminology that is used in ASP.NET MVC.

  • A controller handles HTTP requests and executes application logic.
  • Actions are methods on a controller that get invoked to handle HTTP requests. The return value from an action is used to construct the HTTP response.
  • Routing is the mechanism that selects which action to invoke for a particular HTTP request, usually based on the URL path and the HTTP verb.
  • A view is a component that renders HTML. Controllers can use views when the HTTP response contains HTML.
  • A model is an object that represents the domain data in your application. Typically an app either renders the model as HTML, or serializes the model into a data format such as JSON.
  • Razor syntax is a simple programming syntax for embedding server-based code in a web page.

I’ve defined some of these terms in a way that is specific to ASP.NET. For example, controllers have a particular purpose in ASP.NET MVC, but “model-view-controller” is a more general pattern, used by many frameworks.

Getting Started with ASP.NET vNext

Currently, there is no Visual Studio integration for ASP.NET vNext, so you will build and run applications from the command line.

Use kvm (the version manager) to get the latest version of the runtime. Follow the instructions on the project wiki.

A minimal vNext project contains two files:

  • project.json. This file lists the dependencies for the application.
  • A startup class.

For now, the best way to create a project.json file is to copy the example from HelloMvc sample.

The startup class is where you configure the HTTP request pipeline for your application. Here is a simple example.

using Microsoft.AspNet.Builder;

public class Startup
{
    public void Configure(IBuilder app)
    {
        app.UseWelcomePage();
    }
}

By default , the hosting environment expects the startup class to be named Startup. The startup class must contain a method named Configure with the signature shown here. Inside this method, use the IBuilder interface to configure the application.

The UseWelcomePage methods adds a middleware component that just displays a welcome page. The welcome page is useful for diagnostic purposes, to make sure your project is configured and running correctly.

To start the application, open a command prompt and type the following commands:

kpm restore
k web

The kpm restore command resolves the dependencies listed in the project.json file, and downloads the necessary NuGet packages. The k web command starts the HTTP listener.
Notice there is no explicit build step. The k web command compiles the code on the fly. After you install the NuGet packages, you can make changes to the code and run k web again, without running kpm restore.

Next, launch a browser and navigate to http://localhost:5001. You should see the welcome page.

The web command is defined in the project.json file:

  "commands": {
    "web": "Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:5001"
  },

This command starts the hosting environment and listens on the specified localhost address. You can edit the project.json file to use a different port number.

Serving Static Files

The welcome page is not too interesting, so lets’s enable the app to serve static files. Add the following entry to the “dependencies” section of the project.json file:

"Microsoft.AspNet.StaticFiles": "0.1-alpha-build-0402"

Modify the Startup class as follows.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.StaticFiles;

public class Startup
{
    public void Configure(IBuilder app)
    {
        app.UseStaticFiles();
    }
}

Getting Started with MVC 6

In the rest of this overview, we’ll explore some of the features of MVC 6. To enable MVC, modify the Startup class as follows.

using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

public class Startup
{
    public void Configure(IBuilder app)
    {
        app.UseServices(services =&gt;
        {
            services.AddMvc();
        });

        app.UseMvc(routes =&gt;
        {
            routes.MapRoute(
                name: "Default",
                template: "{controller}/{action}/{id?}",
                defaults: new { controller = "Home", action = "Index" });
        });

    }
}

This code enables MVC and defines a route. If you’ve used earlier versions of MVC, the MapRoute method should look familiar. For comparison, here are the same routes defined in MVC 5 and MVC 6:

// MVC 5 route
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index",
        id = UrlParameter.Optional }
);

// MVC 6 route
routes.MapRoute(
    name: "Default",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" }
);

The ‘?’ character in the template means the {id} segment is optional.

Next, add a controller class. The following controller defines a single action named Index that returns a view.

using Microsoft.AspNet.Mvc;

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Except for the namespace, this code would compile in MVC 5.

Now add a view. Create a file named ./Views/Home/index.cshtml and paste in the following code.

@{
  var message = "Hello World";
}

<!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Index Page</title>
</head>
<body>
  <h1>@message</h1>
  <p>Index page</p>
</body>
</html>

I included a @message variable just to show that this is a Razor file and not just static HTML.

Here is the file structure for the project:

.\HomeController.cs
.\project.json
.\Startup.cs
.\Views\Home\Index.cshtml

Run the app by using the k web command, and then navigate to http://localhost:5001. You should see the HTML that is rendered by the Index view.

View Models

You can pass a model to the view. Let’s add a model class:

public class MessageModel
{
    public string Message { get; set; }
}

Modify the action by passing an instance of MessageModel to the View method:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MessageModel { Message = "Hello ASP.NET" };
        return View(model);
    }
}

Update index.cshtml to refer to the model.

<!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Hello World Page</title>
</head>
<body>
  <h1>@Model.Message</h1>
</body>
</html>

Now when you run the app, “Hello ASP.NET” is rendered inside the H1 tag.

Creating Web APIs and REST-Style Actions

If the route template does not include {action}, the framework uses the HTTP verb to select the action name. This style of routing is similar to convention-based routing in the current version of ASP.NET Web API, and is useful for REST-style APIs.

Here is an example of a route template without an {action} variable.

app.UseMvc(routes =&gt;
{
    routes.MapRoute("ApiRoute", "{controller}/{id?}");
});

Using this route template, the action name maps to the HTTP verb in the request. For example, a GET request will invoke a method named Get, a PUT request will invoke a method named Put, and so forth. The {controller} variable still maps to the controller name.

The following controller uses this style of routing.

using Microsoft.AspNet.Mvc;

public class ValuesController : Controller
{
    // GET /values
    public string Get()
    {
        return "Values";
    }

    // GET /values/1
    public string Get(int id)
    {
        return "Value " + id.ToString();
    }

    // POST /values
    public ActionResult Post()
    {
        return new HttpStatusCodeResult(201);
    }
}

The following table shows the web API that is defined by ValuesController.

Request Method URI Path Controller Action
GET /values Get
GET /values/1 Get(id)
POST /values Post

The two Get actions both return strings. In that case, the framework writes the string into the body of the HTTP response, and sets the Content-Type header to “text/plain”. For example, if you send a GET request to /values/1, the response will look similar to the following.

HTTP/1.1 200 OK
Content-Type: text/plain
Server: Microsoft-HTTPAPI/2.0
Date: Wed, 30 Apr 2014 00:16:38 GMT
Content-Length: 7

Value 1

The Post action returns an HttpStatusCodeResult. The framework translates this into an HTTP status code.

HTTP/1.1 201 Created
Content-Length: 0
Server: Microsoft-HTTPAPI/2.0
Date: Wed, 30 Apr 2014 00:18:58 GMT

If you are familiar with ASP.NET Web API, you may have noticed that ValuesController derives from Controller, not ApiController. That’s because vNext does not have a separate controller class for web APIs.

In the current ASP.NET framework, MVC 5 and Web API 2 use completely different classes and namespaces. That means a controller is either an MVC controller or a Web API controller. Web API controllers use separate routes, and they can’t use MVC filters or MVC model binders.

One goal of ASP.NET vNext is to merge MVC and Web API into a single framework, which shares a single pipeline and uses the same routing, action selection, filters, model binding, and so forth. The result will be a more consistent programming model, and code that is more re-usable.

Returning JSON

To serialize an object into JSON format, call Controller.Json. This method returns a JsonResult, which is an action result that serializes an object to JSON format. For example, let’s add a model class named Movie.

public class Movie
{
    public string Title { get; set; }
    public int Year { get; set; }
    public string Genre { get; set; }
}

Here is a controller that returns a list of movies in JSON format.

using Microsoft.AspNet.Mvc;

public class MoviesController : Controller
{
    public ActionResult Get()
    {
        var movie = new Movie
        {
            Title = "Maximum Payback", Year = 1990, Genre = "Action"
        };
        return Json(movie);
    }
}

The response from the Get action will look similar to the following.

HTTP/1.1 200 OK
Content-Type: application/json
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 02 May 2014 20:39:25 GMT
Content-Length: 120

[{"Title":"Maximum Payback","Year":1990,"Genre":"Action"},{"Title":"Fatal Vengeance 2","Year":2012,"Genre":"Action"}]

Note: The preview release does not support content negotiation yet.

Areas

Areas are a way to group controllers, models, and views. In previous versions of MVC, you register areas by calling AreaRegistration.RegisterAllAreas. Area controllers are placed in a special Areas folder.

In MVC 6, you create a route template with an {area} parameter, and then decorate area controllers with the [Area] attribute. The following code defines an area route.

app.UseMvc(routes =&gt;
{
    routes.MapRoute(
        name: "AreasRoute",
        template: "{area}/{controller}/{action}");

    routes.MapRoute(
        name: "Default",
        template: "{controller}/{action}/{id?}",
        defaults: new { controller = "Home", action = "Index" });
});

Given these routes, you could define two Home controllers, as follows:

namespace MyApp.Controllers
{
    public class HomeController : Controller
    {
        // Home/Index
        public ActionResult Index()
        {
            return View();
        }
    }
}
namespace MyApp.Areas.Controllers
{
    [Area("Books")]
    public class HomeController : Controller
    {
        // Books/Home/Index
        public ActionResult Index()
        {
            return View();
        }
    }
}

The second controller is assigned to the Books area.

URI Controller
/Home/Index MyApp.Controllers.HomeController
/Books/Home/Index MyApp.Areas.Controllers.HomeController

Views for an area go into a folder named “Areas/{area name}/Views/{controller}”. So in this example, the view for the Books/Home/Index action would go in a file named “Areas\Books\Views\Home\index.cshtml”.

Previously, the Web API framework did not support areas. Because MVC 6 merges the two frameworks, you can now organize web API-style controllers into areas.

View Components and Child Views

View components are similar to child actions in previous versions of MVC. They allow a view to invoke an action and render the result within the view. The following code shows a simple view component that writes a text string.

[ViewComponent(Name = "MyViewComponent")]
public class SimpleViewComponent : ViewComponent
{
    public IViewComponentResult Invoke(int num)
    {
        var message = String.Format("The secret code is: {0}", num);
        return Result.Content(message);
    }
}

To include this view component in a view, call Html.Component.

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Index Page</title>
</head>
<body>
  <p>@Component.Invoke("MyViewComponent", 42)</p>
</body>
</html>

When the view is rendered, the p tag will contain the string “The secret code is 42”. Notice that you can pass parameters to the view component’s Invoke method.

POCO Controllers

In MVC 6, controllers do not need to derive from Microsoft.AspNet.Mvc.Controller. You can write a controller as a simple class or “POCO” (plain old CLR object).
Here is an example.

public class HomeController
{
    // Helpers can be dependency injected into the controller
    public HomeController(IActionResultHelper resultHelper)
    {
        Result = resultHelper;
    }

    private IActionResultHelper Result { get; set; }

    public ActionResult Index()
    {
        return Result.Json(new { message = "Poco controllers!" });
    }
}

IActionResultHelper is a helper for creating action results. Notice that the IActionResultHelper instance is injected into the controller via the constructor. The framework provides a default IActionResultHelper implementation, and automatically injects it. You could also provide your own implementation of IActionResultHelper.

Previously, I showed a controller calls Controller.Json to return JSON data. That method is really just syntactic sugar for calling IActionResultHelper.Json.

The Controller class also gives you convenient access to the HTTP request context, the current principal (IPrincipal), a view bag, and other useful properties. So the Controller class is certainly useful, but it’s not required. For a light-weight controller, you might prefer a POCO controller.

Angular js – Calling a function when ng-repeat is finished

I had to call the SyntaxHighlighter/Prismjs to reload once the angularjs loading data is finished. I took some time to figure it out, but finally I found a StackOverflow post which helped me to fix this.

   $scope.$watch("posts", function (value) {
                            //  var pr = new prism();
                            //  pr.load();
                            $timeout(function () {
                                Prism.highlightAll();
                                SyntaxHighlighter.highlight();
                            });
                        });

One can manually load prism syntax and SyntaxHighlighter to apply their syntaxes after the data is loaded
for prism use

  Prism.highlightAll(asyn,callback);

and for SyntaxHighlighter it was eash

  SyntaxHighlighter.highlight();

Angular js – restrict links to page refresh

With the anchor tags and routing used in Angular js Single Page Apps(SPA), we don’t want the entire controller to reload and refresh all the items.
To restrict the anchor tags from refreshing, you can add the directive to the main module

   .directive('a', [
    function () {
        return {
            restrict: 'E',
            link: function (scope, elem, attrs) {

                elem.bind('click', function (e) {
                    if (attrs.ngClick || attrs.href === '' || attrs.href == '#') {
                        e.preventDefault();
                        e.stopPropagation();
                    }
                })
            }
        };
    }
]);

Angular js – Adding scripts dynamically

I have been learning and trying to implement couple of things using Angularjs and Nancy.
NancyFx with owin is fun to start with. I am adding couple of things that took some time to implement and to find online also.

Adding scripts dynamically:
in the main controller add the below function

            $scope.loadScript = (function (url, type, charset) {
            if (typeof (type) == 'undefined') type = 'text/javascript';
            if (url) {
                var script = document.querySelector("script[src*='" + url + "']");
                if (!script) {
                    var heads = document.getElementsByTagName("head");
                    if (heads && heads.length) {
                        var head = heads[0];
                        if (head) {
                            script = document.createElement('script');
                            script.setAttribute('src', url);
                            script.setAttribute('type', type);
                            if (charset) script.setAttribute('charset', charset);
                            head.appendChild(script);
                        }
                    }
                }
                return script;
            }
        });

and in the child controller add the below function

$scope.$parent.loadScript('../Scripts/libs/prism.js', 'text/javascript', 'utf-8');

WPF TemplateSelector for contentTemplate

I wanted to dynamically change template of the tab content based on the tab selected. I used ContentTemplateSelector. It’s so simple:
Write a custom template selector inheriting DataTemplateSelector and override SelectTemplate method

    public class CustomTabItemSelector
        : DataTemplateSelector
    {
        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            FrameworkElement element = container as FrameworkElement;
            if (element != null && item != null && item is object)
            {
                if (item.ToString().ToLower() == "related" || item.ToString().ToLower() == "linked")
                    return element.FindResource("TabContentQuestionDetails") as DataTemplate;
                else if(item.ToString().ToLower() == "comments")
                    return element.FindResource("TabContentComments") as DataTemplate;
                else
                    return element.FindResource("TabContentAnswers") as DataTemplate;
                
            }
            return null;
        }
    }

You need to declare DataTemplates in the ResourceDictionary or in the window resources or any where the element can be able to find the resource

    <DataTemplate x:Key="TabContentQuestions">
            <telerik:RadGridView
                             ItemsSource="{Binding DataContext.Questions, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
                             Height="300" Width="Auto"
                             AutoGenerateColumns="False"
                            x:Name="QuestionGrid" AllowDrop="False"
                             >
                <telerik:RadGridView.Columns>
                    <telerik:GridViewDataColumn Header="Title" DataMemberBinding="{Binding Title}"/>
                </telerik:RadGridView.Columns>
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
                        <i:InvokeCommandAction Command="{Binding DataContext.SelectedQuestionCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" CommandParameter="{Binding ElementName=QuestionGrid, Path=SelectedItem}">

                        </i:InvokeCommandAction>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </telerik:RadGridView>
        </DataTemplate>

you need to add the reference to the customtemplateselector assembly and declare it in the xaml

//refering the assembly
 xmlns:ts="clr-namespace:SomeAssemblyNamespace;assembly:SomeReferencingAssemblyName"

//Declare the customselector
<ts:CustomTabItemSelector x:Key="myCustomTabItemSelector"/>

//Using the selector in the tabcontrol
<telerik:RadTabControl x:Name="SomeTab"
                       ContentTemplateSelector="{StaticResource myCustomTabItemSelector}"
Originally posted on LibrarianShipwreck
The Hearbreak of Heartbleed

Periodically when a person uses a computer one may receive notifications that contain phrases such as “do you trust this connection” or “do you trust this site.” While it is unlikely that such prompts are intended to send users tumbling into an existential abyss they nevertheless carry a very important question bundled in the guise of a simple yes or no (“allow” or “don’t allow”) moment. That question: “do you trust…”

Well…do you?

Using technological systems in contemporary society (in particular “high technological” systems) is often premised upon an oft unspoken level of trust, which relies as much (if not more so) on subconscious consent. We trust that our devices will function the way we have been led to expect them to function, we trust that the applications we use will do what they advertise, we trust that the passwords we use are being kept secret by the sites to which they correspond, we trust that the little “lock” logo that sometimes appears in our web browser actually means something, and so forth.

Using these systems requires such extensive granting of good faith that it becomes second nature. We stop thinking about it, and this is at least partially because investing such trust is necessary if we want to be able to continue using these systems. We trust sites like Yahoo because the seeming societal consensus is they can be trusted. Yet, of late, there have been many instances that have made it so that this subconscious trust has been dredged up to the conscious level and it has forced many to evaluate the way this trust has been placed. Like a closely relied upon confidant being revealed as an enemy spy (at which your life tailspins into a noir film!) this crack in the façade may make lead us to find ourselves feeling a bit heartbroken…or at the very least like we are experiencing heartbleed.

Heartbleed, of course, is the name given to a rather serious bug (even deemed “catastrophic” by some), which has revealed that some of our trust may have been sorely misplaced. The bug has already been gnawing away at sites using OpenSSL for a rather disheartening amount of time, but it has chewed through the surface recently.

So, why does this matter? Well, as the Guardian put it, SSL is a common security tool used online – it allows for the flow of information to be encrypted; what Heartbleed allows is for prying eyes to get a glance at that encrypted data – including passwords and the like. Heartbleed has been sinking its pincers and mandibles into many sites including aspects of the Yahoo empire (like Tumblr), as well as other sites such as Eventbrite, Imgur, and (in a bit of irony) OKCupid. Evidently that was not Cupid’s arrow but the stinger of a bug…

As with all revelations about bugs there is a bit of hyperventilating panic (“catastrophic”) and then the exterminator shows up, makes a droll assessment, sprays some of this and that about, and explains that while the infestation was quite bad it has now been seen to. The exterminator was summoned in time. Phew! Stay away from the worst spots for a few days, keep an eye out, but don’t worry, everything is fine, and if you’re worried here’s a helpful resource, and you can always call the exterminator again. But the issue with such bugs is in that they lay bare, even if only for a moment or two, the degree to which our placing trust in certain technological systems makes us susceptible to certain kinds of bugs.

At risk of being grossly overly simplistic: many people who use high-tech devices and platforms have only a vague understanding of everything (emphasis on everything) that goes on in and around such devices. Even those who consider themselves technologically savvy and quite computer literate might still find themselves stumped by some of the questions that crop up around certain code (which comes in many different languages). After all, Heartbleed is a bug that impacted quite a few prominent platforms (and it is not as if past bugs have not hit other companies [see: Apple]) which were conceivably being managed by highly technologically skilled individuals. All of which is a roundabout way of saying – when we use a high tech device or platform our use of it is in some ways a statement (by deed) of trust. There is only a limited amount of choice (for most people) in this regard – and while there are some options these are generally still options based around which sites we want to trust (Yahoo or Google, Tumblr or Facebook, Apple or Microsoft, etc…). Life in technological society requires placing trust in those building the infrastructure, but it seems that these may not be certified architects…

Part of what makes us so susceptible to unhappy discoveries such as Heartbleed is the fact that high tech devices/platforms put us at a disadvantage in regards to fully understanding our tools – once we decide to use high tech devices we are at their mercy to a certain extent. Consider – as a counter example – a bicycle: a person with a basic manual, some time on their hands, and maybe a helpful friend or two can come to understand how such a machine works, where its problems may be, and how to fix it when things go wrong. It is not quite a “simple machine” but it is “simple enough” that an individual can understand it confidently; it does not have layers of secrets. Now consider a smart phone, a computer or a (closed/proprietary) operating system – a person with a manual, some time on their hands, and maybe a helpful friend or two can learn a great deal – but the sheer complexity of the machine will make it so that their mastery over the device is always wanting, always wanting (exceptions certainly exist, but the majority of users are not exceptions).

The more complicated a device (the less “convivial” [Illich], “democratic” [Mumford] or ”appropriate” [Schumacher]) the more we are forced to put our trust not in our skills, or those of our friends but in those who represent the device – those whose interests are tied up in the device functioning in particular ways. It is not so much that bugs are “catastrophic” accidents as that bugs are part of the deal we consent to when we click “agree” on the Terms of Service contract.

What bugs such as Heartbleed demonstrate to a galling (if not necessarily “catastrophic” extent) is the degree to which our placing of trust may be, if not highly misguided, at least not fully considered. From the NSA revelations to Heartbleed we are witnessing ever more evidence that for all of its utopian promises technological society may just be a wonderful paint job on a building being devoured by termites. When the bugs break through the paint the exterminators descend quickly to sort out the issue, but as long as we stay in this house it will only be a matter of time before we spot evidence of an infestation in another room. The techno-utopians who hurriedly painted the house and their comrades the exterminators may speak convincingly and offer seemingly wonderful things, but it seems increasingly that part of the price of “free” is societal trust. And really, they’ve bought that pretty cheap.

Heartbleed may not lead to many cases of genuine heartbreak, but it should serve as a reason to reassess this relationship – to these companies, and to their tools.

If we insist on dining on the free lunch that tech companies serve up, we cannot be truly surprised when the crunchy content of the sandwich turns out to be bugs.

Powershell module to MapNetworkDrive

At my work, every few days I have to change the user and connect to a network drive. The mapping process every time used to be little bit difficult. I have created some powershell modules which helped me in this process. This is for my reference and if it helps others that’s great:
I have powershell 2.0 so the modules need to be created in VS 2008 for binary type modules, one can create powershell scripts and imports them as modules too. I wrote it in VS 2008, you need to add reference to System.Management and System.Management.Automation.dll(this is in powershell folder).

I wrote 4 different commandlets in this module, each will perform a different functionality.
Get-Drives – Gets all the logical drives and network paths
Get-FreeDriveLetter – Gets the available drive letter in the descending order which can be used.
Map-AuthNetworkDrive – Maps the network drive with the provided credentials or default credentials
Map-DisconnectNetworkDrive – Removes the map

Get-Drives

    [Cmdlet(VerbsCommon.Get, "Drives")]
    public class GetDrives: PSCmdlet
    {
        protected override void ProcessRecord()
        {
            try
            {
                var drives = CommonMethods.GetDrives();

                this.WriteObject(drives, true);
            }
            catch (Exception ex)
            {
                this.WriteError(new ErrorRecord(ex, "1001", ErrorCategory.NotImplemented, null));
            }

        }
               
    }

    //CommonMethods.GetDrives
 internal static IEnumerable<object> GetDrives2()
        {
            IList<object> driveInfo = new List<object>();
            try
            {
                SelectQuery query = new SelectQuery("Select DeviceID, DriveType, ProviderName From Win32_LogicalDisk");
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
                foreach(ManagementObject disk in searcher.Get())
                {
                    driveInfo.Add(new { DeviceID = disk["DeviceID"], DriveType = (DiskType)disk["DriveType"], ProviderName = disk["ProviderName"] });
                }
            }
            catch (Exception ex)
            {
                throw ex;

            }

            return driveInfo;
        }

  public enum DiskType : uint
    {
        Unknown = 0,
        RemovableDisk = 2,
        LocalDisk = 3,
        NetworkDrive = 4,
        CompactDisk = 5,
        RAMDisk = 6
    }

Get-FreeDriveLetter

   [Cmdlet(VerbsCommon.Get, "FreeDriveLetter")]
    public class GetFreeDriveLetter : PSCmdlet
    {
        protected override void ProcessRecord()
        {
            try
            {
                string freeDrive = CommonMethods.GetFreeDriveLetter();

                this.WriteObject(freeDrive);
            }
            catch (Exception ex)
            {
                this.WriteError(new ErrorRecord(ex, "1001", ErrorCategory.NotImplemented, null));
            }
        }
    }

   //in CommonMethods.GetFreeDriveLetter method
      internal static string GetFreeDriveLetter()
        {
            string freeDrive = "";
            string[] driveLetters = { "D:", "E:", "F:", "G:", "H:", "I:", "J:", "K:", "L:", "M:", "N:", "O:", "P:", "Q:", "R:", "S:", "T:", "U:", "V:", "W:", "X:", "Y:", "Z:" };
            var drives = System.IO.DriveInfo.GetDrives().Select(x => x.Name.Replace("\\", ""));
       
            foreach (var s in driveLetters.Reverse())
            {
                if (drives.Contains(s))
                {
                    freeDrive = "";
                }
                else
                {
                    freeDrive = s;
                    break;
                }
            }

            return freeDrive;
        }

For map and unmap I used Windows Script Host object model reference(IWshRuntimeLibrary)

     [Cmdlet("Map","AuthNetworkDrive")]
    public class MapNetworkDrive: PSCmdlet
    {
        [Parameter(Mandatory=true, Position=0,ValueFromPipeline=false)]
        public string UNCPath { get; set; }

        [Parameter(Mandatory=false, Position=1)]
        public PSCredential Credential { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                WshNetwork network = new WshNetwork();
                if (Credential == null)
                {
                    network.MapNetworkDrive(CommonMethods.GetFreeDriveLetter(), UNCPath, false);
                }
                else
                {
                    network.MapNetworkDrive(CommonMethods.GetFreeDriveLetter(), UNCPath, true, Credential.UserName, Credential.GetNetworkCredential().Password);
                }
            }
            catch (Exception ex)
            {
                this.WriteError(new ErrorRecord(ex, "1001",ErrorCategory.MetadataError, null));
            }
        }
    }

    [Cmdlet("Map", "DisconnectNetworkDrive")]
    public class UnMapNetworkDrive : PSCmdlet
    {
        [Parameter(Mandatory=true, Position=0)]
        public string DriveName { get; set; }

        protected override void ProcessRecord()
        {

            try
            {
                
                    IWshRuntimeLibrary.WshNetwork network = new IWshRuntimeLibrary.WshNetwork();
                    network.RemoveNetworkDrive(DriveName, true, true);
                
            }
            catch (Exception ex)
            {
                this.WriteError(new ErrorRecord(ex, "1001", ErrorCategory.MetadataError, null));
            }
        }
    }

Once the build, you can import the module from powershell ise

Import-Module 'module dll path'

this will be available for that session. One can copy to the powershell module path, so that it can be available all the time.

Convert rows to comma separated list and insert in a table

While performing one of my query diagnostics I had to gather some ids from one database server and use those ids in another. The best way was to gather all ids in a comma separated or in a proper list which can be used to insert into a temp table on another sql server.

I used the below query to gather the list of ids separated by ‘UNION ALL SELECT’

SELECT DISTINCT  CONVERT(varchar,ci.Id) + ' UNION ALL SELECT '
				  FROM dbo.Car c (NOLOCK)
				  INNER JOIN dbo.CarItem ci (NOLOCK) on c.CarId = ci.CarId
                   FOR XML PATH('')

The result produced an XML formatted file which I used in another server to insert in a temp table.

In the process I came to know of one restriction of the SQL Server select/insert that the maximum number of rows allowed are only 4096.