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

Tuesday, 30 December 2014

Do not allow Paste any non alphanumeric characters

I don’t want user to allow pasting of any non Alphanumeric characters on a text box.

function funAlpha()
{
  var otxt=document.getElementById('txtName'); 

var val=otxt.value;

 for(i=0;i
   {
     var code=val.charCodeAt(i);
     if(!(code>=65 && code<=91) && !(code >=97 && code<=121) && !(code>=48 && code<=57))
         { otxt.value=""; return ; }    

   }

}

Friday, 12 December 2014

implement idisposable in c# example

static void Main(string[] args)
{
    using (UsingKeyword obj = new UsingKeyword())
    {
       Console.WriteLine(obj.add());
    }
    Console.Read();
}


 Now if we need to perform the clean up using while using our object and facilitate all the above mentioned functionalities we need to implement the IDisposable pattern. Implementing IDisposable pattern will force us to have a Dispose function.
Secondly if the user want to use the try-finally approach then also he can call this Dispose function and the object should release all the resources. 
Lastly and most importantly, lets have a Finalizer that will release the unmanaged resources when the object goes out of scope. The important thing here is to do this finalize only if the programmer is not using the 'using' block and not calling the Dispose explicitly in a finally block.


namespace BasicCsharp
{
    public class UsingKeyword : IDisposable
    {
        public UsingKeyword()
        {
        }

        public int add()
        {
            return 10 + 10;
        }


        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        private IntPtr handle;
        private Component component = new Component();
        private bool disposed = false;


        public UsingKeyword(IntPtr handle)
        {
            this.handle = handle;
        }


        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                    component.Dispose();
                CloseHandle(handle);
                handle = IntPtr.Zero;
                disposed = true;

            }
        }

        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);
    }

}

Thursday, 27 November 2014

How to create Customize permission levels SP2010

let’s run through the steps:
  1. From the site collection click ‘Site Actions’
  2. Click ‘Site Settings’
  3. Under ‘Users and Permissions’ click ‘Advanced Permissions’
  4. You will then see a list for permission level group
  5. Select the ‘Settings’ drop down.
  6. Click ‘Permission Levels’
  7. Click ‘Add a Permission Level’
  8. You will then be able to create your own security group.
Below is a list of permissions that can be set. Please note that selecting one may also result in others being selected because they are required as part of your selection
List Permissions:
  • Manage Lists – create and delete lists, add or remove columns in a list, and add or remove public views of a list.
  • Override Check Out – discard or check in a document that is checked out to another user.
  • Add Items – add items to lists, add documents to document libraries, and add Web discussion comments.
  • Edit Items – edit items in lists, edit documents in document libraries, edit Web discussion comments in documents, and customize Web Part Pages in document libraries.
  • Delete Items – delete items from a list, documents from a document library, and Web discussion comments in documents.
  • View Items – view items in lists, documents in document libraries, and view Web discussion comments.
  • Approve Items – approve a minor version of a list item or document.
  • Open Items – view the source of documents with server-side file handlers.
  • View Versions – view past versions of a list item or document.
  • Delete Versions – delete past versions of a list item or document.
  • Create Alerts – create e-mail alerts.
  • View Application Pages – view forms, views, and application pages. Enumerate lists.
Site Permissions:
  • Manage Permissions – create and change permission levels on the Web site and assign permissions to users and groups.
  • View Usage Data – view reports on Web site usage.
  • Create Subsites – create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.
  • Manage Web Site – grants the ability to perform all administration tasks for the Web site as well as manage content.
  • Add and Customize Pages – add, change, or delete HTML pages or Web Part Pages, and edit the Web site using a Windows SharePoint Services-compatible editor.
  • Apply Themes and Borders – apply a theme or borders to the entire Web site.
  • Apply Style Sheets – apply a style sheet (.css file) to the Web site.
  • Create Groups – create a group of users that can be used anywhere within the site collection.
  • Browse Directories – enumerate files and folders in a Web site using SharePoint Designer and Web DAV (Distributed Authoring and Versioning) interfaces.
  • View Pages – view pages in a Web site.
  • Enumerate Permissions – enumerate permissions on the Web site, list, folder, document, or list item.
  • Browse User Information – view information about users of the Web site.
  • Manage Alerts – manage alerts for all users of the Web site.
  • Use Remote Interfaces – use SOAP, (Simple Object Access Protocol) Web DAV, or SharePoint Designer interfaces to access the Web site.
  • Use Client Integration Features – use features that launch client applications. Without this permission, users will have to work on documents locally and upload their changes.
  • Open – allows users to open a Web site, list, or folder in order to access items inside that container.
  • Edit Personal User Information – allows a user to change his or her own user information, such as adding a picture.
Personal Permissions:
  • Manage Personal Views – create, change, and delete personal views of lists.
  • Add/Remove Personal Web Parts – add or remove personal Web Parts on a Web Part Page.
  • Update Personal Web Parts – update Web Parts to display personalized information.

Saturday, 15 November 2014

Auto select file in Solution explorer from it is open tab in VS2010

Tools ->Option -> project and solution -> Track active item in solution explorer

Step 1: Goto Tool menu and click Option ..

Step 2:  project and solution -> Track active item in solution explorer

Step 3: Output


Programmatically Read Version of a Sharepoint List

Here I will show how you can read all versions of a list item programmatically. As you know, in SharePoint you can turn on the versioning for a list so whenever you modify an item in your list, it keeps track of all your changes so you can revert back to a specific version.


Thursday, 2 October 2014

BUILDING AND USING MS PROJECT 2010 PROXY ASSEMBLY FOR WCF PSI SERVICE

To do the task of integrating Microsoft Dynamics NAV 2009 R2 and MS Project Server 2010 I have decided to use WCF interface. WCF interface is provided by PSI (Project Server Interface) which has both ASMX object model and WCF object model implemented.
There are three options for communicating with WCF interface of MS Project Server:
  1. Compiling ProjectServerServices.dll PSI proxy assembly.
  2. Add a PSI proxy source code to the Visual Studio solution.
  3. Add a service reference by using Visual Studio.
I have decided to use the first option and compile ProjectServerServices.dll proxy assembly.

Project 2010 SDK

First you need to download and install Project 2010 SDK from Microsoft Download site http://www.microsoft.com/en-us/download/details.aspx?id=15511
After you have installed Project 2010 SDK you need to go to the installation folder. In my case that was folder: C:\Program Files (x86)\Microsoft SDKs\Project 2010\Documentation\Intellisense\WCF. Unpack the Source.zip file, found in that folder, so you get the Source subfolder containing C# source files.
Next, you need to start CompileWCFProxyAssembly.cmd to create ProjectServerServices.dll file. The best way to do it is to open Command prompt with administrative privileges (Start->All Programs->Accessories->Command prompt then right click and select Run as administrator), then cd to the C:\Program Files (x86)\Microsoft SDKs\Project 2010\Documentation\Intellisense\WCF and then run CompileWCFProxyAssembly.cmd.

Note: You need to change the path of sn (sn.exe) to the location of Windows SDK in CompileWCFProxyAssembly.cmd. In my case that was C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\x64\sn.exe.

After the script has run you should have ProjectServerServices.dllin this folder.

Visual Studio

In Visual Studio you shoud add reference by clicking right mouse button on Reference folder in your C# project then select Add reference… option, then select Browse on the left hand side of the Reference Manager window and click Browse… button on the lower side of the window. Navigate to C:\Program Files (x86)\Microsoft SDKs\Project 2010\Documentation\Intellisense\WCF\ProjectServerServices.dllfile and click Add button. Click OK to close the Reference Manager window.

project server 2010 requires at least microsoft internet explorer 7.0

My IE to version 10 for Windows2008 r2. Since then, I was not able to access my project centre. I kept getting this error message
 I tried setting the compatibility mode for this PWA site. Note: You can do this via IE Tools.

Flow below steps 
  • Open Internet Options from Tools menu.
  • Click on Security tab in internet option box.
  • Click on Local Intranet, Then click on Sites button. You will get again a box where you have to click on Advanced button.
  • Put project server url here and then click on Add button.
  • Now close all boxes and Refresh your IE.



Thursday, 4 September 2014

Text Box Characters Counter using Javascript

In forms when using text boxes or text areas with limited character length (usually needed for forms that submit data to a database) it is always a good idea to tell the user how many characters they have remaining. This javascript snippet is especially useful for textarea fields since they can't be assigned a text limit in HTML but can be restricted using this code.
The following example shows how you can do this. This is a very simple and cute idea to help the user know exactly how many characters can be typed further. Do these small add-ons to your forms and they will look really professional.

 
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.5.js"></script>
    <script>
    function countChar(val) {
        var len = val.value.length;
        if (len >= 100) {
          val.value = val.value.substring(0, 100);
        } else {
          $('#charNum').text(100 - len);
        }
      };
    </script>
  </head>

  <body>
    <textarea id="field" onkeyup="countChar(this)" ondrop="countChar(this)" onfocus="countChar(this)" onload="countChar(this)"  ></textarea>
    <div id="charNum1">(Maximum characters:<span id="charNum" > 100</span>)</div>
  </body>

</html>

Text box allow only Alphabets

Introduction 
Here I will show how to use Javascript to allow only alphabets in textbox or how to make textbox to allow only alphabets using javascript
 
 
<html>
<div>
               <script type="text/javascript">
                   function IsAlpha(e) {
                      // alert(e.keyCode);
                       var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;

//65 to 90 is Capital letter : 97 to 122 is small letter : 32 is Space  : Delete 127
                       var ret = ( (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <=

           122) || (keyCode == 32) || (keyCode == 08) || (keyCode == 127));
                      // document.getElementById("error").style.display = ret ? "none" : "inline";
                       return ret;
                   }
        </script>
            <input type="text" id="text1" onkeypress="return IsAlpha(event);" ondrop="return false;"
        onpaste="return false;" />

   
        </div>
</html>