Friday, 30 November 2012

Specify Referring Page Using Javascript

Specify Referring Page Using Javascript


This script makes sure that your visitor can only reach a given page from the page that you specify. Paste the following before the ending head tag on the page: 


<SCRIPT LANGUAGE="JavaScript">
var allowedreferrer = "http://www.yoursite.com/referringpagename.htm"; 
if (document.referrer.indexOf(allowedreferrer) == -1) {
alert("You can only access this page from " + allowedreferrer);
window.location=allowedreferrer;
}
</script>

Copy Selected Text Using Javascript


Copy Selected Text Using Javascript


Often you may have some information on your page that your visitors might want to copy. You can make it easier for them by providing a mechanism that allows them to simply click a button to do so. First you need to paste this code into the head of your web page: 


<SCRIPT LANGUAGE="JavaScript">
function copyit(theField) {
 var selectedText = document.selection;
 if (selectedText.type == 'Text') {
  var newRange = selectedText.createRange();
  theField.focus();
  theField.value = newRange.text;
 } else {
  alert('select a text in the page and then press this button');
 }
}
</script>

And in the body of your web page, add the following where you want the text to appear:



<form name="it">
<div align="center">
<input onclick="copyit(this.form.select1)" type="button" 
value="Press to copy the highlighted text" name="btnCopy">
<p>
<textarea name="select1" rows="4" cols="45"></textarea>
</div>
</form>


Disable All Clicks in a Webpage using Javascript

Disable All Clicks in a Webpage using Javascript


If you want to completely disable someone's mouse, try altering either script so that the alert will display no matter what button is pushed.


<SCRIPT LANGUAGE="javascript">
function click() {
if (event.button==1 || event.button==2) {
alert('No clicking!')
}
}
document.onMouseDown=click
</SCRIPT> 

Disable Left Click in Webpage Using Javascript


Disable Left  Click in Webpage Using Javascript


The following Javascript Code Snippet will disable Left Click in the Webpage.. Just keep this code in the head section of the Webpage...


<SCRIPT LANGUAGE="javascript">
function click() {
if (event.button==1) {
alert('No clicking!')
}
}
document.onMouseDown=click
</SCRIPT>

Wednesday, 28 November 2012

Interview with Curt Christianson


Interview with Curt Christianson

 

 

Hi Today I got this opportunity to do an interview with current Microsoft MVP and one of the moderators of ASP.Net Forums Mr. Curt Christiason.

Mr. Curt Christiason is from Plover, WI - USA. He is an 10 time Microsoft  MVP award recipient having more than 20 years of Experience in the IT industry.

You can visit him @ his website http://darkfalz.com/

Here are the glimpses of the Interview:

Q1.Tell Something  About Yourself?
A)     I’ve been around in the IT world, professionally for almost 20 years now. I’m a 10 time Microsoft MVP recipient, focusing mostly on the Web development side of things. I’m a published author on the subject as well as formerly hosting a number of websites dedicated to the subject.

Q2.What do you do?
A)     I’m a professional developer working in the Insurance Industry.

Q3.What is your Development Environment?
A)     My primary environment would be Visual Studio 2010 focusing on ASP.NET using VB.NET. I also run Visual Studio 2012.

Q4.What is your Area of Interest?
A)     Of late my interests have been more around the UI and the interesting things that can be done with jQuery and related technologies. Before this my primary focus was around core frameworks and reusable architectures.

Q5.How did you get started Programming?
A)     I previously worked in the IT Industry as a hardware/networking support person where I worked myself up to be a Corporate Systems Administrator working for a software company that spanned a number of states. Eventually I found myself being bored with this path and started to “tinker” around with some HTML and vbScript (classis ASP). This new opportunity lead me to an opening as a developer and I have been with this ever since. I’m completely self-taught but believe this has been beneficial to my career path.

Q6.How has the developer Community Influenced your coding?
A)     From day 1 (being self-taught) I relied heavily on the community. Newsgroups, and later Forums were where I got almost all of my assistance. It’s safe to say that without a strong community in my early days I would likely not be a developer today.

Q7. Your Role Model/Programmer?
A)     I don’t think I would have any single role model when it comes to programming. There have been a number of people throughout the years that have been influential but nearly all of them are from the online world. For me I would have to say it’s the “Community” as a whole that I would list as my biggest influence and therefore my “role model”.

Q8.Your Favourite Websites and Blogs?
A)     I spend time, nearly every day on the http://forums.asp.net website so this would have to be the foremost entry. After that my focus comes and goes depending on what’s happening. People like Scott Guthrie host some interesting blogs of course but depending on the subject of the posting and it’s pertinence to what I’m currently working on I’m not always reading it.

Q9.Your Hobbies?
A)     As it related to development, I spend a good deal of time working on Open Source projects (like the iTracker project I developed on CodePlex). Outside of that I’m an avid gamer but mostly spend my time with my Family.

Q10.Apart from Programming what do you  do?
A)     Computer gaming, wood working, fishing, hunting and spending time with my wife and children.

Q11. If you were not a programmer  what would be you?
A)     A Chef. I love to cook, always have.

Q12.Your Favourite Holiday Spot?
A)     Las Vegas if I’m with friends, Wisconsin Dells if I’m with my family.

Q13.Advice to New Programmers ?
A)     Keep at it. Nearly every aspect of existing development has already had it’s major hurdles overcome so rely on the Community for support when it comes to ways to best utilize these. Instead, focus on the things that haven’t been done. Find ways to better development as a concept, not just develop better.
 


Saturday, 24 November 2012

Find the length/Duration of Audio File


Find the length/Duration of Audio File


Method 1:

You will need to reference Windows Media Player. Go to Com Add-ins to add the wmp.dll to your project.


string Duration = null;
WMPLib.WindowsMediaPlayer w = new WMPLib.WindowsMediaPlayer();
WMPLib.IWMPMedia mediaFile = w.newMedia(Filename);
if (mediaFile != null) {
   Duration = mediaFile.durationString;
}
w.close();



Method 2:

Add Reference to Shell32.dll.


private string GetDuration(string FileFullPath) { string duration = "";  
string fName = FileFullPath.Substring(FileFullPath.LastIndexOf("\\") + 1); 
string filePath = FileFullPath.Substring(0, FileFullPath.LastIndexOf("\\"));  
Shell32.Shell shell = new Shell32.ShellClass(); 
Shell32.Folder folder = shell.NameSpace(filePath);  
Shell32.FolderItem folderItem = folder.ParseName(fName);  
if (folderItem != null) { 
duration = folder.GetDetailsOf(folderItem, 21); } 
folderItem = null; 
folder = null; 
shell = null; return duration; } 



Method 3:


using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Sound
{
    public static class SoundInfo
    {
        [DllImport("winmm.dll")]
        private static extern uint mciSendString(
            string command,
            StringBuilder returnValue,
            int returnLength,
            IntPtr winHandle);

   public static int GetSoundLength(string fileName)
      {
       StringBuilder lengthBuf = new StringBuilder(32);

       mciSendString(string.Format("open \"{0}\" type waveaudio alias wave", 
       fileName),null, 0, IntPtr.Zero); 
 
       mciSendString("status wave length", lengthBuf, lengthBuf.Capacity, 
       IntPtr.Zero); 
 
       mciSendString("close wave", null, 0, IntPtr.Zero);

       int length = 0; 
 
       int.TryParse(lengthBuf.ToString(), out length);

       return length;
      }
    }
}


 
 
References:

http://stackoverflow.com/questions/82319/how-can-i-determine-the-length-of-a-wav-file-in-c
http://msdn.microsoft.com/en-us/library/system.windows.controls.mediaelement.aspx

For Video Files:

http://forums.asp.net/p/1245309/2295602.aspx
 
 
 

Thursday, 22 November 2012

Using Java Jar or Class File in ASP.Net/ Convert Jar to dll

Using Java Jar or Class File in ASP.Net/ Convert Jar to dll


Even wondered how to use a Java or Jar file in .Net ?
Well, the answer can be complicated or it can be simple too.

Complicated - This way would be to deal with interops. You would have to load the JVM and then interop the java calls across.
Simple way - Use ikvm.net. Using ikvm we can convert java/jar file to a .net dll. And well then it’s all good and easy.
IKVM is a free tool and has a bunch of other Java-.Net related support.

How  It Works:

The ikvmc tool generates .NET assemblies from Java class files and jar files. It converts the Java bytecodes in the input files to .NET CIL. Use it to produce
  • .NET executables (-target:exe or -target:winexe)
  • .NET libraries (-target:library)
  • .NET modules (-target:module)
Java applications often consist of a collection of jar files. ikvmc can process several input jar files (and class files) and produce a single .NET executable or library. For example, an application consisting of main.jar, lib1.jar, and lib2.jar can be converted to a single main.exe.
When processing multiple input jar files that contain duplicate classes / resources, ikvmc will use the first class / resource it encounters, and ignore duplicates encountered in jars that appear later on the command line. It will produce a warning in this case. Thus, order of jar files can be significant.

Examples

ikvmc myProg.jar 
 
Scans myprog.jar for a main method. If found, an .exe is produced; otherwise, a .dll is generated.

ikvmc -out:myapp.exe -main:org.anywhere.Main -recurse:bin\*.class lib\mylib.jar
 
Processes all .class files in and under the bin directory, and mylib.jar in the lib directory. Generates an executable named myapp.exe using the class org.anywhere.Main as the main method.

For More Details Visit this Link:

 http://www.codeproject.com/Articles/13549/Using-Java-Classes-in-your-NET-Application

Alternatively,

http://www.jnbridge.com/

Replace Selected Text in a Textbox Using Javascript


Replace Selected Text in a Textbox Using Javascript


The following code snippet demonstrates how to get the selected text from a Text box and then replace it with some different text using JavaScript.

The following code snippet gets the selected text only from the Text box and then this text is processed and updated to the text box.

<script type="text/javascript">

    function formatselection() {

        var textbox = document.getElementById('inputTextBox');
        var textSelected;
        var formattedText;

        if (document.selection != undefined) {//IE

            textbox.focus();
            var sel = document.selection.createRange();
            textSelected = sel.text;
        }
        else if (textbox.selectionStart != undefined) {//Mozilla

            var startSelPos = textbox.selectionStart;
            var endSelPos = textbox.selectionEnd;
            textSelected = textbox.value.substring(startSelPos, endSelPos);
        }

        if (textSelected != null && textSelected != "") {

            formattedText = textSelected.replace(new RegExp("a", 'g'), "b");

            var finaltext = textbox.value;
            finaltext = finaltext.replace(textSelected, formattedText);

            document.getElementById('inputTextBox').value = finaltext;
        }
    }
</script>



The above function replaces all a’s in the selected text with b’s.
The above code uses two ways to get the selected text. The two methods are for different browsers;Mozilla, IE.
Here is a demo code:


<html>
<title>Format</title>
<head>
<script type="text/javascript">

    function formatselection() {

        var textbox = document.getElementById('inputTextBox');
        var textSelected;
        var formattedText;

        if (document.selection != undefined) {//IE

            textbox.focus();
            var sel = document.selection.createRange();
            textSelected = sel.text;
        }
        else if (textbox.selectionStart != undefined) {//Mozilla

            var startSelPos = textbox.selectionStart;
            var endSelPos = textbox.selectionEnd;
            textSelected = textbox.value.substring(startSelPos, endSelPos);
        }

        if (textSelected != null && textSelected != "") {

            formattedText = textSelected.replace(new RegExp("a", 'g'), "b");

            var finaltext = textbox.value;
            finaltext = finaltext.replace(textSelected, formattedText);

            document.getElementById('inputTextBox').value = finaltext;
        }
    }
</script>
</head>
<body>
<div>
        <hr color="orangered" style="height: 1px;"/>

        <h1 style="color: navy; font-size: 20px;">Format your resouce code</h1>

        <table>
        <tbody>
         <tr>
            <td valign="TOP">
                <b>Enter text:</b>
                <br/>
                <input type="textarea" style="height: 251px; width: 737px;" 
               id="inputTextBox" cols="20" rows="2" name="inputTextBox"/><br/>
            </td>

        </tr>
        <tr>
            <td valign="TOP">
                Select some text and then Hit on Format button.
               All a's in selected text will be converted to b's
                <br/><br/>
                <input type="submit" id="btnFormatToHTML" value="Replace" 
                 name="btnFormatToHTML" OnClick="formatselection()"/>
                  <br/>
                <br/>

            </td>
            <td valign="TOP">

            </td>

        </tr>
        </tbody></table>
        <br/>
     </div>
</body>
</html>



Copy this code to an file and name it as Default.Html. Double click the file, it will open in a browser. Rest of the instructions are given on the page.

Validation and Javascript


Validation and Javascript


Most of the Asp.Net programmer use different validation control to validate user input. But basically so many developers do not know how it works. Validation controls are use to validate user input and it is basically work as JavaScript, so we can use this validation controls instead of writing JavaScript to validate user input. The main advantage of this validation control is that it can be use with the web browser which has disabled the JavaScript or browser does not support JavaScript, because even when validation cannot happen on client side, validation still perform on server side.

            If the user has disabled the JavaScript in their web browser the page will post-back to the server without performing client side validating and the code will execute related the button’s click event (i.e.: Entry to the DB it will create fake or Null). But you can stop this by validate this user input at server side. For that you have to check following property Page.IsValid. It will return true if the validation control does not have any error or it will return false if validation control contain error.

            It is easy to forget that to check Page.IsValid property because you always work with the web browser which has enabled JavaScript.

Refer:
http://stackoverflow.com/questions/5534336/how-to-handle-validation-when-javascript-is-disabled-in-asp-net
http://forums.asp.net/t/1666400.aspx/1

Thursday, 15 November 2012

Get Drive Name of Connected USB using C#


Get Drive Name of Connected USB using C#


Get drive letters of connected USB storage devices. These can then be used in file I/O operations.

using System.Management;

Code: 

private static List<string> GetConnectedUsbDrives()
{
    List<string> usbDriveLetters = new List<string>( );

   var usbDrives = new ManagementObjectSearcher( "SELECT DeviceID FROM Win32_DiskDrive WHERE InterfaceType='USB'" );

    foreach ( ManagementObject drive in usbDrives.Get( ) )
    {
        var partitions = new ManagementObjectSearcher( "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive[ "DeviceID" ].ToString( ) + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition" );

        foreach ( var partition in partitions.Get( ) )
        {
            var logicalDrives = new ManagementObjectSearcher( "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition[ "DeviceID" ].ToString( ) + "'} WHERE AssocClass = Win32_LogicalDiskToPartition" );

            foreach ( var logicalDrive in logicalDrives.Get( ) )
            {
                usbDriveLetters.Add( logicalDrive[ "Caption" ].ToString( ) );
            }
        }
    }

    return usbDriveLetters;
}


Implementation:


static void Main ( string[ ] args )
{
    foreach ( var s in GetConnectedUsbDrives() )
    {
        Debug.WriteLine( "Drive : " + s );
    }

    Console.ReadLine( );
}

   

Clean File and Folders Using C#

Clean File and Folders Using C#


Clean File:

        public static bool CleanupFile(string path)

        {

            try

            {

                if (File.Exists(path))

                {

                    File.SetAttributes(path, FileAttributes.Normal);

                    File.Delete(path);

                }

                return true;

             }

            catch

            {

               return false;

            }

        }


Clean Folder:


        public static bool CleanupFolder(string folder)

        {

            try

            {

                if (Directory.Exists(folder))

                    Directory.Delete(folder, true);

                return true;

            }

            catch

            {

                return false;

            }

        }

Creating Time Delay Programmatically C#

Creating Time Delay Programmatically C#


Wait a certain number of seconds before doing another action.


        void LightWait(int waitTime)

        {

            int curSecond = Convert.ToInt32(DateTime.Now.ToString("ss"));

            int newSec = curSecond + waitTime;

            if (newSec > 59)

            {

                newSec = newSec - 60;

            }

            while (!(Convert.ToInt32(DateTime.Now.ToString("ss")) == newSec))

            {

                Application.DoEvents();

            }

        }

Note:

Paste this into your main form. (Not in any other void)

To wait:
LightWait(10); //this will wait for 10 seconds.

Download a file Programmatically C#


Download a file Programmatically C#


Use the following Code-Snippet to Download a particular file-type Programmatically:


FileStream fs; 
object strPath = "C:\\My External\\File Path\\"; 
string strFileName = "7f0873f1.mp3"; 

// Check Validation Here
if (true) 
{ 
 fs = File.Open(strPath + strFileName, FileMode.Open); 
 byte[] bytBytes = new byte[fs.Length]; 
 fs.Read(bytBytes, 0, Convert.ToInt32(fs.Length)); 
 fs.Close(); 
 Response.AddHeader("Content-disposition", "attachment; filename=" + strFileName); 
 Response.ContentType = "application/octet-stream"; 
 Response.BinaryWrite(bytBytes); 
 Response.End(); 
} 
else 
{ 
 // Error
}

Get Browser Info


Get Browser Info


Get Few Details Regarding the Browser on which this Page is Displayed:


<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Get Browser Info</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <h3>Request.Browser Info:</h3>

<table border=1>

<tr><td>User Agent</td><td><% Response.Write(Request.ServerVariables["http_user_agent"].ToString());%></td></tr>

<tr><td>Browser</td><td><% Response.Write(Request.Browser.Browser.ToString());%></td></tr>

<tr><td>Version</td><td><% Response.Write(Request.Browser.Version.ToString());%></td></tr>

<tr><td>Major Version</td><td><% Response.Write(Request.Browser.MajorVersion.ToString());%></td></tr>

<tr><td>Minor Version</td><td><% Response.Write(Request.Browser.MinorVersion.ToString());%></td></tr>

<tr><td>Platform</td><td><% Response.Write(Request.Browser.Platform.ToString());%></td></tr>

<tr><td>ECMA Script version</td><td><% Response.Write(Request.Browser.EcmaScriptVersion.ToString());%></td></tr>

<tr><td>Type</td><td><% Response.Write(Request.Browser.Type.ToString());%></td></tr>

<tr><td colspan=2>&nbsp;</td></tr>

<tr><td>ActiveX Controls</td><td><% Response.Write(Request.Browser.ActiveXControls.ToString());%></td></tr>

<tr><td>Background Sounds</td><td><% Response.Write(Request.Browser.BackgroundSounds.ToString());%></td></tr>

<tr><td>AOL</td><td><% Response.Write(Request.Browser.AOL.ToString());%></td></tr>

<tr><td>Beta</td><td><% Response.Write(Request.Browser.Beta.ToString());%></td></tr>

<tr><td>CDF</td><td><% Response.Write(Request.Browser.CDF.ToString());%></td></tr>

<tr><td>ClrVersion</td><td><% Response.Write(Request.Browser.ClrVersion.ToString());%></td></tr>

<tr><td>Cookies</td><td><% Response.Write(Request.Browser.Cookies.ToString());%></td></tr>

<tr><td>Crawler</td><td><% Response.Write(Request.Browser.Crawler.ToString());%></td></tr>

<tr><td>Frames</td><td><% Response.Write(Request.Browser.Frames.ToString());%></td></tr>

<tr><td>JavaApplets</td><td><% Response.Write(Request.Browser.JavaApplets.ToString());%></td></tr>

<tr><td>JavaScript</td><td><% Response.Write(Request.Browser.JavaScript.ToString());%></td></tr>

<tr><td>MSDomVersion</td><td><% Response.Write(Request.Browser.MSDomVersion.ToString());%></td></tr>

<tr><td>TagWriter</td><td><% Response.Write(Request.Browser.TagWriter.ToString());%></td></tr>

<tr><td>VBScript</td><td><% Response.Write(Request.Browser.VBScript.ToString());%></td></tr>

<tr><td>W3CDomVersion</td><td><% Response.Write(Request.Browser.W3CDomVersion.ToString());%></td></tr>

<tr><td>Win16</td><td><% Response.Write(Request.Browser.Win16.ToString());%></td></tr>

<tr><td>Win32</td><td><% Response.Write(Request.Browser.Win32.ToString());%></td></tr>

</table>

    </div>

    </form>

</body>

</html>

Links for Various Forums ASP.NET


Links for Various Forums ASP.NET






Here is a list of links to the forums related to ASP.Net:


Access
ActiveX Development
AspDotNetStorefront
BizTalk

BlogEngine.NET
Bug Reports and Suggestions for Microsoft
Cassini Web Server
Cat.Net (static code checker for SQL and XSS Injection)
Certifications and Training
Cheat Sheets
CkEditor
Classic ASP
Code Converters (convert VB to C# and C# to VB)
Cognos
Commerce Server
ComponentArt
Cross Browser Compliance
Cruise Control
Crystal Reports
C#
Delphi
Developer Express
Doloto
Dot Less
Dot Net
DotnetNuke
Dreamwaver
Dundas Chart
Entity Framework
Expression Web
Facebook
FckEditor - see CKEditor

FFMPEG
Firebird

Flash

Foxpro
Free Asp.Net Web Hosting
FXCOP
F#
Generic Programming Sites
GhostDoc
Git
Googlemaps
IIS and Classic Asp
Infragistics

Internet Explorer

iTextSharp
Java
jQuery
JSON
LINQ
Live Meeting
MBUnit
Microsoft Charting Control
Microsoft Infopath
Microsoft Office
Microsoft Project
MOQ
MySQL
NANT Forum
NHbernate
NOPCommerce
Notepad++
Open Source Projects and Libraries
Oracle
Pex
PHP
Powershell
Print XML
Regular Expressions

Sharepoint
Sharpdevelop
Siebel
Silverlight
Smart Devices
Source Control (including Source Safe)
SQL Compact/Mobile
SQL Server:
SQL Server Express
SQL Server Setup and Getting Started

SSIS
SSRS
StyleCop (a.k.a. CodeCop)
SugarCRM
SVN
Sybase
Terminal Services
TinyMCE
Telerik Controls
Tortoise SVN
Ultidev
Umbraco

Unity
Upload Source Projects to
VideoLAN
Visual Basic
Visual Studio Debugger
Visual Studio Express Edition
Visual Studio LightSwitch
Visual Source Safe (VSS)
Visual Studio Team System (VSTS)
Visual Studio Team Version Database Version
Visual Studio Extensibility

Visual Studio and .NET Framework documentation
VSTO Visual Studio Tools for Office
Web Hosting:
Windows 7
Windows Azure Development
Windows Communication Foundation (WCF)
Windows Forms
Windows Mobile
Windows Presentation Form (WPF)
Windows Server 2008
Windows Services
Windows SysInternals
Windsor Castle
Yet Another Forum
back to top