Sunday 16 August 2015

How do I convert a text file to an Excel file with validation using C#?


Text file Format

C# Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

namespace text_excel
{
    class Program
    {
        static void Main(string[] args)
        {

            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            Excel.Range chartRange;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            string line;
            using (StreamReader reader = new StreamReader(@"yourFilePath.txt"))
            {
                int lineNo = 4;
                ArrayList list = new ArrayList();
                int[] arr4 = new int[100];
                while ((line = reader.ReadLine()) != null)
                {
                    
                    int colomnNo = 2;
                    string[] words = line.Split('|');
                    int startno = 0;
                    if (line.StartsWith("Sriram validation"))
                    {
                        string output = line.Replace("Sriram validation | ", "");
                        string[] numbers = output.Split('|');
                       
                        foreach (string nos in numbers)
                        {   
                            arr4[startno] = Convert.ToInt16(nos);
                            startno++;
                        }
                    }
                    else
                        foreach (string word in words)
                        {
                            string wordcount = word.Trim();
                            xlWorkSheet.Cells[lineNo, colomnNo] = wordcount;
                            if (arr4[startno] == wordcount.Length)
                                 xlWorkSheet.Cells[lineNo, colomnNo].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
                            else if (arr4[startno] < wordcount.Length)
                                xlWorkSheet.Cells[lineNo, colomnNo].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
                            else if (arr4[startno] > wordcount.Length)
                                xlWorkSheet.Cells[lineNo, colomnNo].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue);
                            colomnNo++;
                            startno++;
                        }
                    lineNo++;
                }
            }
            xlWorkSheet.get_Range("b2", "e3").Merge(false);

            chartRange = xlWorkSheet.get_Range("b2", "e3");
            chartRange.FormulaR1C1 = " Validation";
            chartRange.HorizontalAlignment = 3;
            chartRange.VerticalAlignment = 3;
            chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
            chartRange.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
            chartRange.Font.Size = 20;

            xlWorkBook.SaveAs("d:\\csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlApp);
            releaseObject(xlWorkBook);
            releaseObject(xlWorkSheet);
        }

        private static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                //MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        } 
    }
}

Output :


Saturday 15 August 2015

text to speech in c#



First, we need to reference the System.Speech assembly from the application. From the Project menu, choose Add Reference. The from the .NET tab, highlight System.Speech and choose OK.

Declarations

Next, we need to declare and instantiate a speech object. The class isSystem.Speech.Synthesis.Speechsynthesizer. This one class has enough properties and methods to speak a string using the default language and voice of the OS. In Microsoft Windows Vista, the default voice is Microsoft Ana. 


protected void ibtnSpeaker_Click(object sender, ImageClickEventArgs e)
        {
            Thread t = new Thread(() =>
            {
                SpeechSynthesizer audio = new SpeechSynthesizer();
                audio.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Senior); // to change VoiceGender and VoiceAge check out those links below
                audio.Volume = 100;  // (0 - 100)
                audio.Rate = -1;     // (-10 - 10)
                audio.Speak(lblQuestionStart.Text);
            });
            t.Start();
        }

Thursday 30 July 2015

How to remove unused using namespaces

 Visual Studio can do this for you.
Organise Usings > Remove Unused Usings
I am using this all the time, to clean up code, and make code compilation quicker.
Or you can use PowerCommands to remove unused usings for entire projects

Install this Microsoft-created add-in, and VS 2010 will always remove and sort usings every time you save a code file (e.g. with Ctrl-S or clicking a Save button).
The option is under Tools > Options > PowerCommands > Remove and Sort Usings on save. There's also an option to automatically format the document on Save, which will make sure your code lines up, doesn't include trailing spaces, etc.
(Should you need to avoid removing and sorting usings while this is installed, just build or run your code without explicitly saving. The automatic save-on-build or save-on-run will still happen.)

Monday 25 May 2015

Understanding LINQ in One-Liners

Here I will provide one liner-explanations of terminology used with LINQ.
  • From: initialize a data source just like we declare a variable first before using it in C#.
  • where: applies a condition in a LINQ query.
  • select: selects a value from the LINQ query.
  • var: assigns a variable for when we don't know the return type of our LINQ query.
  • Deffered execution: the LINQ query will store only the information, it will not provide the result directly to you. To get the result you need to use a foreach loop or toList or ToArray method. Until this stage LINQ is in the deffered execution stage.
  • foreach loop: to iterate the result that we got from the LINQ query and then to execute the result.
  • IEnumerable: use this if you know that your LINQ query return type will be a string and the data is in your in-memory.
  • IQueryable: use this if the query is generated using a database.
  • Lambda expression: use the => operator if you are using a method-based LINQ query. The left hand of the => operator is the input and the right hand side is the output.
  • Expression lambda: use an expression lambda if you want to pass an expression on the left hand side of the => operator.
  • Statement lambda: If you want to use a statement in the right hand side of the => operator then use the statement lambda enclosed in brackets {}.
  • Async Lambda: use this if you want to use async or await in your LINQ query.
  • Async and await: to do asynchronous programming like if one resource is busy then the other program will keep executing, it will not wait for completion of the resource task.
  • let: use the let keyword when you want to store the result of any expression inside the LINQ.
  • LINQ to SQL: use this if you want to access a collection from a SQL Server in your in-memory.
  • System.Data.Linq.dll: add this DLL if you want LINQ to SQL.
  • insertonsubmit: use this when you want to insert data into SQL using LINQ to SQL.
  • deleteonsubmit: use this when you want to delete data in SQL using LINQ to SQL.
  • submitchanges: use this in LINQ to SQL after insertonsubmit or deleteonsubmit or if you have updated any data in your in-memory collection. This will submit your data finally to the database.
  • LINQ to dataset: use this if you want to query your in-memory dataset.
  • System.Data.DataSetExtensions: use this DLL if you want to use LINQ to a dataset.
  • asenumerable: use this if you want to apply LINQ to a datatable since a datatable doesn't implement ienumerable or iqueryable.
  • field: use the field method in LINQ to access a datatable column using LINQ to dataset.
  • setfield: use SetField if you want to set column values in a DataRow using LINQ to dataset.
  • isnull: use isnull if you want to check that a column is null or not using LINQ to dataset.
  • join: use this if you want to join two datatables using LINQ to dataset.
  • groupjoin: use this when you want a superset of inner joins and left outer joins.
  • LINQ to Objects: use this if you want to apply the LINQ on an array, list or dictionary.
  • LINQ to XML: use this if you want to do manipulation with XML or if you want to create new XML using LINQ.
  • Distinct: use this with your LINQ query if you want to remove duplicate values from a collection.
  • Except: use this with LINQ if you want to return the set difference of two collections.
  • Intersect: use this if you want to return common data from two collections in LINQ.
  • Union: use this when you want all elements from both collections but the result should not contain duplicate data.
  • All: use this in LINQ if you want to check that your condition is satisfying all the elements of a collection.
  • Any: use this in LINQ if you want to check your condition with any element in a collection.
  • Contains: use this if you want to check whether or not a sequence contains a specified element.
  • Skip: use this if you want to skip elements up to a specified position in a sequence.
  • SkipWhile: use this if you want to skip elements until the condition is true.
  • Take: use this if you want to take the first n elements from a sequence.
  • Takewhile: use this if want to take all the elements when the condition becomes true.
  • concat: use this if you want to combine two sequences, it may contain duplicate values also.
  • AsQueryable: use this if you want to convert a generic Ienumerable type to a generic IQueryable Type.
  • Cast: use this if you want to cast an element of a sequence in any other type.
  • ToArray: use this if you want to convert your collection into an array and if you want to force query execution.
  • ToDictionary: use this function if you want to put your element into a dictionary based on key. This will also force query execution.
  • ToList: use this if you want to convert collections into a generic list. This will also force query execution.
  • ToLookup: this is also like a dictionary but with a one-to-many relationship. Use this if you want to put your element into a dictionary.
Refer: http://www.c-sharpcorner.com/UploadFile/3dc6f6/linq-understanding-in-one-liner/

Sunday 19 April 2015

Sharepoint Central administration gives a blank page after installing Sharepoint 2007 on Windows 7 64bit


The problem is getting a blank page instead of Central Administration after the configuration of Sharepoint on the machine
Cause of the problem:
The following authentication mechanisms are not installed or disabled on the IIS
  1. Digest Authentication
  2.  Basic Authentication
  3. Windows Authentication
To install them open command prompt and run the following command
Command 
start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-ManagementScriptingTools;IIS-Security;IIS-BasicAuthentication;IIS-WindowsAuthentication;IIS-DigestAuthentication;IIS-RequestFiltering;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-IIS6ManagementCompatibility;IIS-Metabase;IIS-WMICompatibility;WAS-WindowsActivationService;WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI;WCF-HTTP-Activation;WCF-NonHTTP-Activation

The command will be executed and you can see in IIS that these authentication mechanisms will be added. See the sample screenshot below:



Please make sure that the Windows Authentication should be enabled to access the SharePoint 2010 central administration page.

So, now you can browse the central admin page instead of blank page.

Disabled New Application Button in Central Administrator Sharepoint 2010



  1. Go to control Panel (win + r  shortcut key for run textbox and type control)
  2. Click on System and Security
  3. Under “Action Center” section , click on “Change User Account Control settings”
  4.  Scroll down the scrollbar to “Never Notify” as shown in below figure
  5.  Click on Ok
  6.  Restart the system ( This step is necessary)
  7. Now open the central administration as administrator
  8. Now the New Web Application button is enabled
NewWebDisabled


Friday 13 March 2015

How to print a number with commas as thousands separators in JavaScript

I would like to format a currency with $ in JavaScript.


        function numberWithCommas(currency) {
           
            var decimalplaces = 2;
            var decimalcharacter = ".";
            var thousandseparater = ",";
            currency = parseFloat(currency);
            var sign = currency < 0 ? "-" : "";
            var formatted = new String(currency.toFixed(decimalplaces));
            if (decimalcharacter.length && decimalcharacter != ".") { formatted = formatted.replace(/\./, decimalcharacter); }
            var integer = "";
            var fraction = "";
            var strnumber = new String(formatted);
            var dotpos = decimalcharacter.length ? strnumber.indexOf(decimalcharacter) : -1;
            if (dotpos > -1) {
                if (dotpos) { integer = strnumber.substr(0, dotpos); }
                fraction = strnumber.substr(dotpos + 1);
            }
            else { integer = strnumber; }
            if (integer) { integer = String(Math.abs(integer)); }
            while (fraction.length < decimalplaces) { fraction += "0"; }
            temparray = new Array();
            while (integer.length > 3) {
                temparray.unshift(integer.substr(-3));
                integer = integer.substr(0, integer.length - 3);
            }
            temparray.unshift(integer);
            integer = temparray.join(thousandseparater);

            // Here we are showing alert message
            alert(sign + integer + decimalcharacter + fraction);
        }


TextBox ID="txtnumber" runat="server" onblur="numberWithCommas(this.value);"

Sunday 1 February 2015

Top in SQL SERVER 2008


The TOP keyword allows you to return the first n number of rows from a query based on the number of rows or percentage of rows that you define.
The first rows returned are also impacted by how your query is ordered.
In previous versions of SQL Server, developers used SET ROWCOUNT to limit rows returned or impacted.

We can use the top keyword with the following queries:
Select
Insert
Delete
Update
Basically, most of us know about top, we can use it in a select query to get the top element from the query.

But top can also be used in Insert, Delete and Update commands for the table as well.

We will see how we can use top with Insert, Delete and Update.

1 Top with select statement

Syntax: - SELECT TOP 10 * FROM
Example:- 
SELECT top(1) Name,Class,Age,Address,Phone,Pin FROM [dbo].[SampleTable]


2 Top with Insert Statement

It is when we have to insert only the top few records that we can use this:

Syntax:-
 

Insert top (10) into (column1, column2.....)
Select column1, column2..... From
 
or
 
Insert into (column1, column2.....)
Select TOP (10) column1, column2..... From
 

Example:-
 
INSERT TOP (2) INTO [dbo].[SampleTable1]
SELECT Name,Class,Age,Address,Phone,Pin FROM [dbo].[SampleTable]

ORDER BY Class DESC

SELECT Name,Class,Age,Address,Phone,Pin FROM [dbo].[SampleTable]


SELECT Name,Class,Age,Address,Phone,Pin FROM [dbo].[SampleTable1]




 Top with Delete Statement

Deleting top records from a table:

Syntax: -
 Delete top (10) from where

Example:-
 

SELECT  Name,Class,Age,Address,Phone,Pin FROM [dbo].[SampleTable]
DELETE Top(1) FROM [SampleDB].[dbo].[SampleTable]
SELECT  Name,Class,Age,Address,Phone,Pin FROM [dbo].[SampleTable]

Top with Update statement

Updating top records from a table:

Syntax: -
 Update top (10) set Colmn1= 

Example: -
 
SELECT  Name,Class,Age,Address,Phone,Pin FROM [dbo].[SampleTable]
UPDATE TOP (1) [dbo].[SampleTable] SET Class='Hindi' WHERE Class='Msc'
SELECT  Name,Class,Age,Address,Phone,Pin FROM [dbo].[SampleTable]





.

Thursday 29 January 2015

How to print DIV contents only



function printdiv(printpage)
{
var headstr = "";
var footstr = "
";var newstr = document.all.item(printpage).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}










The Div content which you want to print






Ref: http://forums.asp.net/t/1261525.aspx?How+to+print+DIV+contents+only