Wednesday, June 18, 2014

Image Processing in .NET

.Net provides the core for Faster Image Processing using System.Drawing assembly and System.Drawing namespace.

 

Basic About Image

Raster Images are consists of Rows and Columns of Pixels.

A Pixel consists of bytes of values for Pixel

A pixel with 4 bytes usually consists of Alpha, Red, Green and Blue values

A pixel with 3 bytes usually consists of Red, Green and Blue values

A pixel with less than 3 bytes needs further processing like expansion or look up to built 3/4 byte Pixel

 

Steps for Image Processing

Thursday, June 05, 2014

Write DataTable as CSV Text File Using C#

Find below the code that write data from DataTable as a CSV text file

 

Using Section

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

 

Methods for Writing data to CSV

public static DataTable WriteCSV(String filename, DataTable table) {
    var csvData = new DataTable();
    StreamWriter csvFile = null;
    try {
        csvFile = new StreamWriter(filename);

        // Write header
        csvFile.WriteLine(
                String.Join(",",
                    from DataColumn dc in table.Columns
                    select dc.ColumnName)
            );

        foreach (DataRow dr in table.Rows) {
            csvFile.WriteLine(
                    String.Join(",",
                        from DataColumn dc in table.Columns
                        select dr[dc])
                );
        }
    }
    finally {
        if (csvFile != null)
            csvFile.Close();
    }

    return csvData;
}
private static String CsvValue(Object obj) {
    if (obj == null)
        return "";
    else if (obj.GetType() == typeof(String) || obj.GetType() == typeof(DateTime))
        return "\"" + obj.ToString() + "\"";
    else
        return obj.ToString();
}

Parse CSV Text File to Data Table Using C#

Find below a code that parses the CSV text file and give you the records as a Data Table

 

Using Section

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

 

Methods for Parsing CSV

public static DataTable ReadCSV(String filename) {
    var csvData = new DataTable();
    StreamReader csvFile = null;
    try {
        csvFile = new StreamReader(filename);

        // Parse header
        var headerLine = csvFile.ReadLine();
        var columns = ParseCSVLine(headerLine);
        columns.ForEach(c => csvData.Columns.Add(c, typeof(String)));

        var line = "";
        while ((line = csvFile.ReadLine()) != null) {
            if (line == "") // Skip empty line
                continue;
            csvData.Rows.Add(
                ParseCSVLine(line) // Parse CSV Line
                    .OfType<Object>() // Convert it to Object List
                    .ToArray()   // Convert it to Object Array, so that it can be added to DataTable
            ); // Add Csv Record to Data Table
        }
    }
    finally {
        if (csvFile != null)
            csvFile.Close();
    }

    return csvData;
}

private static List<String> ParseCSVLine(String line) {
    var quoteStarted = false;
    var values = new List<String>();
    var marker = 0;
    var currPos = 0;
    var prevChar = '\0';

    foreach (Char currChar in line) {
        if (currChar == ',' && !quoteStarted) {
            AddValue(line, marker, currPos - marker, values);
            marker = currPos + 1;
            quoteStarted = false;
        }
        else if (currChar == '\"')
            quoteStarted = (prevChar == '\"' && !quoteStarted)
                ? true
                : !quoteStarted;
        currPos++;
        prevChar = currChar;
    }
    AddValue(line, marker, currPos - marker, values);
    return values;
}

private static void AddValue(String line, Int32 start, Int32 count, List<String> values) {
    var val = line.Substring(start, count);
    if (val == "")
        values.Add("");
    else if (val[0] == '\"' && val[val.Length - 1] == '\"')
        values.Add(val.Trim('\"'));
    else
        values.Add(val.Trim());
}

Wednesday, June 04, 2014

Visual Studio 14 CTP available for Download

Details: Visual Studio “14” CTP now available
Download links: Visual Studio "14" CTPs

Technology improvements (KB-2967191- Visual Studio "14" CTP release notes)

ASP.NET and web development

  • ASP.NET vNext: This release of Visual Studio supports creating and developing ASP.NET vNext applications. ASP.NET vNext is a lean and composable .NET stack for building modern web applications for both cloud and on-premises servers. It includes the following features:
  • ASP.NET MVC and Web API have been unified into a single programming model. 
  • A no-compile developer experience.
  • Dependency injection out-of-the-box.
  • Side-by-side: Deploy the runtime and framework by using your application.
  • NuGet everything, even the runtime itself.
  • All open source is on the .NET Foundation and takes contributions.
  • For more information about ASP.NET vNext in Visual Studio, go to the ASP.NET vNext website.
  • This release of Visual Studio also includes all the current ASP.NET and web development features that are released as parts of Visual Studio 2013 Update 2. Learn more here.

Managed languages

  • The core IDE and editing experiences for C# and Visual Basic have been replaced with new experiences that are built on the .NET Compiler Platform "Roslyn." Generally, the experience should be unchanged. However, there are numerous small improvements.
  • C# refactoring support has been completely revamped. There are two new core refactorings: Inline Temporary Variable and Introduce Explaining Variable. Additionally, refactoring support for Visual Basic has been added for the first time.
  • You can use specific code-aware guidance for the Microsoft platforms and NuGet packages that you're targeting to obtain live code analysis and automatic fixes as you type.

Visual C++

  • Generalized lambda capture: You can assign the result of evaluating an expression to a variable in the capture clause of a lambda. This allows an instance of a move-only type to be captured by value.
  • User-defined literals in the language and standard library: You can append numeric and string literals with meaningful suffixes to give them suitable semantics. The compiler transforms these suffixes into calls to appropriate UDL-operator functions. The <chrono>, <string>, and <complex> headers now provide literal operators for convenience. For example, "1729ms" means std::chrono::milliseconds(1729), "meow"s meansstd::string("meow"), and 3.14i means std::complex<double>(0.0, 3.14).
  • Completed noexcept: You can check whether an expression will throw an exception by using the noexceptoperator. For example, noexcept(func()) will return "true" if func was specified as noexcept.
  • Inline namespaces: You can specify a nested namespace as "inline" to make its contents accessed from its parent namespace.
  • Thread-safe "magic" statics: Static local variables are initialized in a thread-safe way, removing the need for manual synchronization. Be aware that usage of these variables other than initialization is still not protected. Thread safety can be disabled by using /Zc:threadSafeInit- to avoid a dependency on the CRT.
  • Unrestricted unions: You can define unions that contain types with non-trivial constructors. Constructors for such unions have to be manually defined.
  • Finally, all new C++ 11 and C++ 14 language features that are released in the November 2013 compiler CTP for Visual Studio 2013 are also included in this preview. For more information about these features, read thisannouncement. Briefly, these include the following:
  • __func__extended sizeof, implicit move generation, ref-qualifiers ("&" and "&&" for member functions),alignof and alignas, and inheriting constructors.
  • auto function return type deductiondecltype(auto), and generic lambdas with a limitation of not using [=]/[&] default capture together with generic lambdas. This will be enabled also for generic lambdas in a future release.
  • Resumable functions and awaitproposed for the C++ Concurrency Technical Specification.
  • Null forward iterators: The Standard Library's forward iterators (and stronger) now guarantee that value-initialized iterators compare as equal. This makes it possible to pass an empty range without a parent container. Be aware that generally, value-initialized iterators still cannot be compared to iterators from a parent container.
  • quoted(): These manipulators let iostreams preserve strings that contain spaces.
  • Heterogeneous associative lookup: When it is Enabled by special comparators (such as the less<> and greater<>transparent operator functors), the ordered associative containers gain templated lookup functions. This lets them work with objects that are comparable to keys, without actually constructing keys.
  • integer_sequence: Compile-time integer sequences are now supported to make template metaprogrammingeasier.
  • exchange(): This small utility function makes it convenient to assign a new value to an object and retrieve the old value.
  • get<T>(): This lets a tuple element be accessed by its type (when unique) instead of by its index.
  • Dual-range equal(), is_permutation(), mismatch(): C++98's "range-and-a-half" algorithms that are taking (first1, last1, first2) are difficult to use correctly. While they are still provided, C++14 has added overloads taking (first1, last1, first2, last2) which are significantly easier and safer to use.
  • tuple_element_t: This alias template is added for convenience and consistency with the type traits alias templates.
  • Filesystem "V3" Technical Specification (TS): The interface and implementation of <filesystem> are overhauled to follow this TS, which is likely to be incorporated into C++17.
  • Library Issues: 24 resolutions have been implemented (for example, is_finalmake_reverse_iterator()), not including the resolutions that were already implemented in Visual C++ 2013. Notice that a library issue is a bug report for the Standard. It can be resolved by fixing a specification problem or even adding a small feature.
  • <chrono> fixes: The clocks are rewritten to be conformant and precise.
  • Minimal allocator fixes: Several library components (including basic_string and std::function) did not work with user-defined allocators implementing C++11's minimal allocator interface, instead requiring C++03's verbose allocator interface. All occurrences of this problem are fixed.
  • C99 library features: Most of the remaining C99 library features are implemented.
  • snprintf is implemented.
  • The printf and scanf families of functions now support the new C99 format string improvements.
  • The strtod and scanf families of functions now support hexadecimal floating-point.
  • Library conformance is better improved by software updates and adjustments.
  • __restrict: The __restrict keyword is now supported on reference types in addition to pointer types.
  • Improved diagnostics: The compiler will now emit warnings about suspicious code that previously would not have resulted in warnings. For example, shadowed variables will now cause warnings. Warnings have also been made clearer.
  • The /Wv flag: You can use /Wv:XX.YY.ZZZZ to disable warnings that are introduced after compiler version XX.YY.ZZZZ. Notice that the emitted warnings may still differ from those emitted by the specified version.
  • Compiler software updates: We have fixed more than 400 bugs in the compiler. 179 of these were submitted by users through Microsoft Connect.
  • Refactored C Runtime (CRT): This CTP contains the first preview of the substantially refactored CRT.
  • msvcr140.dll no longer exists. It is replaced by a trio of DLLs: vcruntime140.dll, appcrt140.dll, and desktopcrt140.dll.
  • stdio performance: Many performance improvements are made in the stdio library, notably in the sprintf andsscanf families of functions.
  • Object file size reductions: Working together with compiler fixes, the STL's headers are changed to significantly reduce the sizes of object files and static libraries (that is after compilation but before linking. The sizes of linked EXEs/DLLs are unaffected). For example, when you compile a source file that includes all C and C++ Standard Library headers and does nothing else with them, for x86 with /MD /O2, Visual C++ 2013 generated a 731 KB object file. This is improved to be less than 1 KB.
  • Debug checking fixes: The STL's debug checks rejected null pointers that are passed as iterators, even when the Standard guaranteed that they should work (for example, merging two [null, null) ranges to a null output). Every algorithm is inspected and fixed.
  • Create declaration or definition: You can quickly create a function’s declaration or definition in relation to its neighbors. To do this, right-click the declaration or definition, or use SmartTags.
  • Debugger visualizers: Natvis debugger visualization files can be added to a Visual C++ project for easy management and source control integration. Natvis files that are added to a project will take evaluation precedence over visualizers outside the project.
  • Native memory diagnostics:
  • You can start a memory diagnostic session (Alt+F2) that monitors the live memory usage of your native application. This supports Windows Desktop.
  • You can capture heap snapshots of the running process in memory to see the types and instances for native allocations.
  • You can view the difference in memory allocations between two memory snapshots.
  • You can dive into the memory contents of a process snapshot by using the debugger for deeper analysis of the heap.