Friday, September 30, 2011

Simple javascript to compare date


function CompareDate()
{
var Date1 = document.getElementById('uxDate');
var SplitDate1 = Date1.value.split("/");
var dd1=SplitDate1[1];
var mm1=SplitDate1[0];
var yy1=SplitDate1[2];
var startDate = new Date(yy1,mm1-1,dd1);
var endDate = new Date();

if(startDate >= endDate)
{
alert("Start date should not greater then end date");
return false;
}
else
{
return true;
}

}

Create XML file in javascript from Gridview

Please find below JS for creating xml file from grid using javascript




function CreateXMLFromGrid()
{

var gvControl = document.getElementById('<%= grid1.ClientID %>');
var gvControlID = '<%= grid1.ClientID %>';
// hidden id so xml is stored here
var uxhdnXML = document.getElementById('<%= uxhdnXML.ClientID %>');

var strOut;
strOut = "";

for (i = 0; i <= gvControl.rows.length - 2; i = i + 1)
{
// will set grid row index
if (parseInt(i + 2) <= 9)
midfix = '0' + parseInt(i + 2);
else
midfix = parseInt(i + 2);

// text box control in grid
var txtbox = document.getElementById(gvControlID + '_ctl' + midfix + '_txt1');
// Drop down list control in grid
var ddllist = document.getElementById(gvControlID + '_ctl' + midfix + '_ddl1');
// Radio button list control in grid
var rblist = document.getElementById(gvControlID + '_ctl' + midfix + '_rdl1');


var resvalue = null;

if (txtbox != null)
{
resvalue = txtbox.value;
if (resvalue == "")
{
resvalue = "NULL";
}
}

if (ddllist != null)
{
resvalue = ddllist.value
if (resvalue == "")
{
resvalue = "NULL";
}
}

if (rblist != null)
{
// below will check from dropdown list weather radio button is checked or not

var checkBoxArray = rblist.getElementsByTagName("input");
for (var j = 0; j < checkBoxArray.length; j++)
{
if (document.getElementById(gvControlID + '_ctl' + midfix + '_rdlSetupvalue' + '_' + j.toString()).checked == true)
{
var checkBoxRef = checkBoxArray[j];
var labelArray = checkBoxRef.parentNode.getElementsByTagName("label");
resvalue = labelArray[0].innerHTML;
break;
}
}
if (resvalue == "")
{
resvalue = "NULL";
}
}

strOut = strOut + "";
strOut = strOut + "" + resvalue + "";
strOut = strOut + "
";

}

strOut = strOut + "
";
// assign created xml to hidden value
uxhdnXML.value = strOut;

}

Friday, August 26, 2011

Maintain scroll position after postback in Asp.Net

Way 1.


Write below mention directive in page directive section of html source of aspx page to maintain scroll position of only one page or selected pages rather then whole web application.


Page Language="VB" AutoEventWireup="false" MaintainScrollPositionOnPostback="true" CodeFile="Default.aspx.vb" Inherits="_Default"

Way 2.

To maintain scroll position programmatically use code mentione below.

System.Web.UI.Page.MaintainScrollPositionOnPostBack = true;

Way 3.

To maintain scroll position application wide or for all pages of web application we can write below mentioned code in pages section of web.config file so that we don't need to add page directive in each and every page.

in web.config page section add maintainScrollPositionOnPostBack="true"

Saturday, April 2, 2011

Remove Duplicates from Generic list

Hi Guys,

Please find below function to remove duplicate irems/objects from generic list

Tuesday, February 22, 2011

.Net 4.0 New Features

1. Setting Meta Tags

Setting Meta Tags with the Page.MetaKeywords and Page.MetaDescription Properties
Two properties have been added to the Page class: MetaKeywords and MetaDescription. These two properties represent corresponding meta tags in the HTML rendered for a page, as shown in the following example:

Keywords="This is the default page" Description="This is the default page" in page or code file

These two properties work like the Title property does, and they can be set in the @ Page directive. For more information, see Page.MetaKeywords and Page.MetaDescription.

Wednesday, February 2, 2011

Copy To Clipboard

Just call below javascript in your code. it will copy div tag data to excel sheet

function copyToClipboard(){
//document.getElementById('copyDiv').focus();
var text = document.getElementById('copyDiv').innerHTML;
if (window.clipboardData.setData("TEXT", text)){
alert("switch to excel and click paste");
}else{
alert("Oops, that didn't work?");
}
}

Friday, January 7, 2011

Creating Windows Service

Create Simple Windows Service

-- Open Studio 2010 >> File >> New >> Project >>
-- Select Visual C# >> Windows >> Windows Service
-- Gave Name to "TestWinService"
-- In .cs file there is two functions where service start/stop
protected override void OnStart()
{
}
protected override void OnStop()
{
}

-- we can use two approch to implement service to run

1) Using System.Timers

// initialize timer object
System.Timers.Timer timertest;

protected override void OnStart()
{
EventLog.WriteEntry("Timer Started at " + DateTime.Now, System.Diagnostics.EventLogEntryType.SuccessAudit);
timertest = new System.Timers.Timer();

this.timertest.Interval = Convert.ToDouble("12000");
this.timertest.Enabled = true;
this.timertest.Elapsed += new System.Timers.ElapsedEventHandler(timertest_Tick);
}


void timertest_Tick(object sender, EventArgs e)
{
try
{
// Service Logic

}
catch (Exception ex)
{
EventLog.WriteEntry(ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
}
}

protected override void OnStop()
{
timertest.Enabled = false;
}

2) Using Thread

System.Threading.Thread workerThread1;

protected override void OnStart(string[] args)
{

System.Threading.ThreadStart st1 = new System.Threading.ThreadStart(FunctionServicelogic);
workerThread1 = new Thread(st1);
// set flag to indicate worker thread is active
service1Started = true;
// start the thread
workerThread1.Start();
}

protected override void OnStop()
{
service1Started = false;
}

private void FunctionServicelogic()
{
while (service1Started)
{
// Service logic
if (service1Started)
{
Thread.Sleep(new TimeSpan(0, 10, 0));
}
}
// time to end the thread
Thread.CurrentThread.Abort();
}

--- You can Build service. Service build sucessfully

--- In the Properties dialog box, click Add Installer.
--- In the Properties dialog box for ServiceInstaller1, change the ServiceName property to LogWriterService.
--- In Design view, click ServiceProcessInstaller1 in the Code Editor.
--- In the Properties dialog box, change the Account property to LocalSystem. The LocalService value and the NetworkService value are only available in Microsoft Windows XP and later operating systems.

-------- Install Windows Service -----------
1) Command Prompt C:\Windows\Microsoft.Net\Framework\v2.0.50727\installutil -i "Service.exe path"
-- -i is for install
-- -u is for uninstall

-------- Varify Windows Service ------------

--- Click Start, point to Control Panel, point to Administrative Tools, and then click Services.
--- Right-click LogWriterService, and then click Start.
--- To verify that an event is logged in the event log, use one of the following methods:
Click Start, point to Control Panel, point to Administrative Tools, and then click Event Viewer. In the left pane, click Application Log. In the right pane, locate the event log for your service.

Thursday, October 28, 2010

Needed

I want to integrate Bombay Stock Exchange Quates in my Website in asp.net. please any one suggest me

Monday, July 26, 2010

Difference between ‘==’ and ‘===’ operator in JavaScript

Check Below two javascript functions

function testEqualfn()
{
var a = 10;
var b = "10";
if (a == b)
{
alert("They are equal");
} else {
alert("They are not equal");
}
}

function testTripleEqualfn()
{
var a = 10;
var b = "10";
if (a === b) {
alert("They are equal");
} else {
alert("They are not equal");
}

So, why "10" and 10 are equal when using == operator and not equal when using === operator.

Please find below reasons for operators.

"==" operator compares only the values of the variables. If the types are different a conversion is operated. So the number 10 is converted to the string "10" and the result is compared.

"===" operator compares not only the values but also the types, so no cast is operated. In this case "10" !== 10

Monday, June 14, 2010

Call page method in javascript

1) create one function

public string getMenu()
{
return (Functions.GetPath() + "/js/jqueryq.js");
}

2) Add function name to Design

script type="text/javascript" language="javascript" src='<%= getMenu() %>' /script

Wednesday, April 28, 2010

Highlight Textbox onfocus

Step -1 Add below Css in Head tag of Html.

.input_text
{ border:1px solid #cEcEcE;
padding:4px;
font-size:14px;
color:#000000;
background-color:#ffffff;
}

.input_text:focus, input.input_text_focus
{
border-color:#646464; background-color:#ffffc0;
}


Step-2 Add Below Javascript for Hovr/Out text box

setAspnetTextFocus = function() {

var classBlur = 'input_text';
var classFocus = 'input_text_focus';
var inputElements = document.getElementsByTagName('input');

for (var i = 0; i < inputElements.length; i++) {
inputElements[i].onfocus = function() {
if (this.className == 'input_text') {
this.className += ' ' + classFocus;
} }
inputElements[i].onblur = function() {
this.className = this.className.replace(new RegExp(' ' + classFocus + '\\b'), '');
} } }

if (window.attachEvent) window.attachEvent('onload', setAspnetTextFocus);

Step -3 Add CSS to text box

ID="TextBox1" runat="server" CssClass="input_text"

Monday, April 19, 2010

Filter Rows from Dataset

Filter Rows from dataset

Step - 1 Convert Datatable to Dataview

DataTable dt = ViewState["MyDataTable"] as DataTable;
DataView dvMyDataTable = dt.DefaultView;

Step - 2 Apply filter conditions in dataview

dvMyDataTable.RowFilter = "DatatableField_Name = " + "My Name";

Step - 3 save data after filter

dt.AcceptChanges();

Tuesday, March 2, 2010

Safari Compatibility patch for WebKit for AJEX

'asp:ScriptReference Path="~/scripts/SafariHackCode.js"' Add reference to SafariHackCode.Js in Script manager

create SafariHackCode js with following code

Sys.Browser.WebKit = {}; //Safari 3 is considered WebKit
if( navigator.userAgent.indexOf( 'WebKit/' ) > -1 )
{
Sys.Browser.agent = Sys.Browser.WebKit;
Sys.Browser.agent = Sys.Browser.WebKit;
Sys.Browser.version = parseFloat( navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
Sys.Browser.name = 'WebKit';
}

Wednesday, December 23, 2009

Working with LINQ and Web Application with Business logic

Here is the steps to create Linq project

Step- 1 Create Blank solution named LinqTest

Step- 2 Add New Class Library named LingTest.DataModel

Add DBML file and from server explorer bind server connection
Add tables, procedures to Dbml file

Step- 3 Add New Class Library named LinqTest.DataAccess

 Add Reference from project LingTest.DataModel
 Create new class called UserDataAccess
 Add following namespaces in UserDataAccess class

using System.Collections.Generic;
using System.Linq;
using LinqTest.DataModel;
using System.Data.SqlClient;
using System.Data.Linq;
 Create methods as follows

public class UserDataAccess
{
// is derived from LinqTest.Datamodel
LinqTestDataContext db;
// User is table object
public int InsertUser(User user)
{
db = new LinqTestDataContext();
int returnvalue = 0;
int? UserId = 0;
try
{
returnvalue = db.Usp_InsertUser(ref ReturnId,parameters……….);
return Convert.ToInt32(UserId);
}
catch (Exception ex)
{
throw ex;
}
}

// Usp_SelectAllResult is procedure name in database
public List GetAllUsers(string username)
{
try
{
using (db = new LinqTestDataContext())
{
var selectedUsers = db.Usp_SelectAll(username);
List lstUsers = new List(selectedUsers);
return lstUsers;
}
}
catch (SqlException ex)
{
throw new LinqTestException("Unable to Get Details . Please try After some time.", ex);
}
catch (LinqTestException)
{
throw;
}
catch (Exception ex)
{
throw ex;
}
}


Step- 4 create one web application called LinqTest.Web
 Add Reference from project LingTest.DataModel , LingTest.DataAccess
 Add following namespaces in UserDataAccess class
using System.Collections.Generic;
using System.Linq;
using LinqTest.DataModel;
using System.Data.SqlClient;
using System.Data.Linq;
LingTest.DataModel call following function to get data
public void BindGrid()
{
List list = new UserDomain().GetAllUsers(“ ”); gridname.DataSource = list;
gridname.DataBind();
}
public void InsertUser()
{
LinqTest.DataModel.User obj = new User();
obj.Username = "name";
obj.password="12345";
int retval = new UserDomain().InsertUser(obj);
BindGrid();
}

Saturday, August 22, 2009

Send mail from Asp.Net

Use follwing class for sending Mail ,attachment in asp.net

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;

///
/// Email class
///

public static class Email
{
public static bool SendMail(string msgFrom, string msgTo, string msgSubject, string msgBody, bool highPriority,string Filename)
{
MailMessage mailMsg = new MailMessage();
SmtpClient smtp = new SmtpClient();
mailMsg.From = new MailAddress(msgFrom);
mailMsg.To.Add(msgTo);
mailMsg.Subject = msgSubject;
mailMsg.Body = msgBody;
mailMsg.IsBodyHtml = true;
if (highPriority) mailMsg.Priority = MailPriority.High;

if (Filename != "")
{
Attachment attachfile = new Attachment(Filename);
mailMsg.Attachments.Add(attachfile);
}
try
{
smtp.Send(mailMsg);
return true;
}
catch (Exception myEx)
{
return false;
}
}
}

Friday, November 21, 2008

Display message box in ASP.Net

Create Simple class

public class MessageBox
{

private System.Web.UI.Page _Objp;
public MessageBox(System.Web.UI.Page page)
{
_Objp = page;
}
public void Show(string Message)
{
string script = "";
_Objp.Response.Write(script);
}

}

-- In Web Page .....

Create Object of Messagebox class

MessageBox _ObjMessageBox = new MessageBox();

_ObjMessageBox.Show("HI");

Tuesday, November 18, 2008

Serialization in .NET

Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is deserialization, which converts a stream into an object. Together, these processes allow data to be easily stored and transferred. There are two types binary serialization and xml serialization. here is the example of binary serialization.

// Serialization
public byte[] getByteArrayWithObject(object o)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(ms, o);
return ms.ToArray();
}

// deserilization
private Object getObjectWithByteArray(byte[] arrBytes)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
Object obj = (Object)binForm.Deserialize(memStream);
return obj;
}

Wednesday, April 16, 2008

Java Script References

1. close form after some time intervals

setTimeout('self.close()',5000);

-- > where self.close() close the form and 50000 is 5 seconds so, form is closed after five seconds

2. Refresh Parent Window after closing Popup window

function refreshParent()
{
window.opener.location.href = window.opener.location.href;
if (window.opener.progressWindow)
{
window.opener.progressWindow.close()
}
window.close();
}

3. Set URL as Homepage

function setHome()
{
document.body.style.behavior='url(#default#homepage)';
document.body.setHomePage("http://www.yoursitename.com");
}

4. Display Digital Clock

function clock()
{
var digital = new Date();
var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();
var amOrPm = "AM";
if (hours > 11) amOrPm = "PM";
if (hours > 12) hours = hours - 12;
if (hours == 0) hours = 12;
if (minutes <= 9) minutes = "0" + minutes; if (seconds <= 9) seconds = "0" + seconds; var a = digital.getMonth(); var b = a + 2 - 1; dispTime = +" "+hours + ":" + minutes + ":" + seconds +''; document.getElementById('Span1').innerHTML = dispTime; setTimeout("clock()", 1000); } window.onload=clock;

5 Disable right clicking on your site to prevent people from stealing your images and code!

function click(e) {if (document.all) {if (event.button == 2) {alert(message);return false;}}if (document.layers) {if (e.which == 3) {alert(message);return false;}}}if (document.layers) {document.captureEvents(Event.MOUSEDOWN);}document.onmousedown=click;

Monday, April 7, 2008

Search Engine Optimization (SEO)



What is SEO(Search Engine Optimization)?

SEO is the process of optimizing a website by improving on site and off site aspect in order to increase the traffic, your sites receives from search engine.

SEO aim to index and improve ranking for the webpages which are most relevent to the keywords searched.

SEO will make site search engine friendly so that our potential customers can find us very easily when surfing the web.

SEO is also called as organic or natural results because we do not have to pay to search engine to get listed in search engine database and to archive high ranking on desired keywords.

Background

Why a company or a website need SEO?

Major traffic on a web sites are coming from well-known search engine like Yahoo, Google and MSN. if you will not submit your site in search engine then your site would not be found on search engine result pages so when visitors use search enginee, they can't find your site whether your site provide best content, product or services. your company van miss the valuable chance available on the website through search engine. so, search engine is the basic method of navigation for almost all internet users.

Once you will submit your site in search engine, after your site must be optimized for search
engine to improve rankings on desired keywords.

Site will be optimized mainly through 2 factors. i.e Onpage Optimization and offpage
Optimization.

Why a website can't get top rankings without SEO help?

When u submit your site in search engine, it will be stored in search engine database. nowadays online business is becoming very competitive so there will be lots of sites related to your site in search engine database then how can your site get high rankings without SEO help.

Every search engines are using their algorithm to giving a ranking priority to the websites.
however there will be a limit that how search engines are working, so right step can create a great traffic of visitors at your site and wrong step can down rankings of your site in search engine results pages(SERPs).

There are two types :

1. Onpage Optimization
2. Offpage Optimization

What is Off Page Optimization:

Off Page Optimization is one of the main factor of Search Engine algorithm. Off Page Optimization means that have an effect on web page listing in SERPs (Search Engine Result Pages). These factors are off site in which you or the coding on your site can not control them. All the things are depend on other sites. Google gives more emphasis on Off Page Optimization.

Off-page optimisation (off-page SEO) is what can be done off the pages of a website to maximise its performance in the search engines for target keywords related to the on-page content and keywords in off-page direct-links.

Off Page Optimization Factors:
-


1. Web site URL submission in search engine: -
First
of all you have to submit your website url in search engine database. URL submission in search engine are free of cost. When you submit your site in search engine, it will be stored in search engine database. If you will not submit your site in search engine, then search engine would not find it and it will be listed in SERPS. Search Engine may take some time(maximum 8 days) to
listed your site in search engine database.

2. Web directory submission or Web promotion: -
Web directory is not like search engine and does not display list of website based on keywords. web directory list the websites by category and subcategory. web directories allows website owners to submit their website in their web directory.

There are thounds of web Free web directories and Paid web directories in which you can submit your site into proper category or related category and promote your website in world wide web.
You need Title, Keywords, Description, URL, and E-ID to submit your site in web directory.

3. Web Building: -
The process of getting maximum links from related, equality and high page rank site to get high page rank and to get high rankings in SERPs.

Link building can be done by three ways:-
1. One way link
2. Two Way Link
3. Three Way Link
4. Blog Creation and Submission: -

If you have specific and unique content related to your site, you can create blog related to your site. You can keep back link of your site in blog so that it will create great traffic at your site and it will be One Way link for your site.

You can submit your blog into thousand of free and paid blog submission sites and it will increase popularity of your site and create targeted traffic at your site. You can keep important information about your site, so if visitors likes your content then it will create potential traffic
for your site.

5. Press Release and Submission: -
You can write press
release about your site or about your new product, after that you can submit your press release to different press release submission site and news publishing sites so it will make popular your site or new products and it will create a targeted traffic to your site.

6. Article Creation and Submission: -
You can create a unique article related to your site and there are so many sites willing to accept well-written articles. By writing articles, it can generate lots of targeted traffic to your site.

7. RSS (Really Simple Syndication) Feed:
RSS feed is used to publish frequently updated content to the subscriber users of your site. If your site has RSS feed and any user will subscribe in RSS feed than that user will get the update of your site when you update your site. So it will create a great traffic of old visitors at your site. When you update any content in your site, you will not need to promote the new content. It will automatically update to the subscribed users.

On Page Optimization:
-


Every Search Engines are using their own algorithm and onpage optimization is also an important factor of search engine's algorithm. onpage optimization means we have to optimize some factor in our web site to make site search engine friendly.

On Page Optimization's Factor: -

1. Keywords: -
Keywords is one of the main factor of on page optimization. People are using phrase or request to get information from website. That phrase or request is called keyword. If you want to build new web site then you have to make some keyword research related to your site. From keyword research you can get list of keyword related to your site which are used by visitors in search engine. You can select keyword research by some following steps.

> Brainstorming: -
Brainstorming means you have to identify your customers mind that means which keywords they are finding in search engine to find information, product or services your sites offers.

> Customer Survey: -
You can make customer survey from past and potentional customers about keywords. From customer survey you can increase your keyword list and you can find potentional keywords.

>Keyword research tool: -
There are many keyword research tool available for free on the internet. There are well known keyword research tool that are wordtracker(it use it's own database) and overture(it use yahoo's database). In keyword research tool, you have to just enter your main keyword of the page, KW
research tool will return all the main keywords related to your entered keyword that means related to your site. It will also return the competition of every keywords.

> keyword selection: -
You can get list of related keywords from keyword research tool, after that you have to select right keywords from that list. you can select right keywords from some intellegent process that means which keyword will give you high conversion rate, which keyword will give you expected traffic at your site.

> Finalize the keywords and implete keywords: -
After passing from all intellegent process, you can get list of keywords so after that you have to implete those keywords in your site and based on that keywords you can write best and unique content for your site so that content will become search engine friendly. From selecting right keywords your site can get top ranking in the search engine results. and from selecting wrong keywords your site may never seen in search engine result pages.

2. Title: -
Title is also an important factor of search engine. Title means summery of the page. it should contain all the major keywords of the page. Title should be specific and unique because it will be
displayed at the search engine result pages so from title any visitors will get idea about the page and about the site. Title should be like it must attract to visitors to select the title and to visit your website.

3. Meta Description: -
Description will be displayed at the search engine result pages under title so it is also an important factor of on page optimization.

4. ALT Tags: -
Alt tag means alternative. Google and other search engine can not read images. they can read only coding of the page. so we should use Alt tag on images. From Alt tag search engine can read what the image is about.

5. Content: -
All the major keywords are used frequently in the content in a natural way. All the main keywords should be highlighted by making them bold, italic or underline. By highlighting the
keywords, we will indicate to search engine about the keywords. Content must be unique it should not be duplicate otherwise it will hurt your search engine rankings. All the major search engines like Goggle, Yahoo and MSN gives more emphasis on the content. If you have good keyword list, best title contains the main keywords and the unique content based on the selected keywords than your site may get the top rankings in the search engine.

6. Keyword Density: -
Keyword density means how many times your keywords are repeating in the content in a natural way. So when the spiders will come on our site to crawl, they can find the keywords easily that is searched by the user in search engine. Some times people are doing keyword stuffing to maintain the keyword density but it is bad for search engine. If you have 100 words in one paragraph and if 4 words from 100 words are your main keyword than it is called 4% keyword density. Generally 5 to 6% keyword density should be maintained in the content.

7. Headings: -
Our main keywords should be used as a Heading. So that it will be very useful for search engine and visitors of the site. You can use the HTML Tags H1 to H6 to make the headings in the content. H1 can be used for main heading and main keyword and than h2 to h6 tags are used for
subheadings and other useful keywords. By headings you can indicate the search engine and your visitors about the keywords.

8. Sitemap :-
Sitemap is very useful for visitors and search engines both. Because visitor can reach at any page of the site within two clicks. Sitemap should be at the top of site so when visitor will come, he can go directly at the sitemap and from sitemap visitor can go directly at any page of the site.

It is also helpful to search engine because when spiders will crawl that sitemap link at that time it
will crawl all the pages of our site. So it can be also useful to your site.

9. Google Sitemap: -
The above sitemap was general for visitors and all the search engines. You can also create a sitemap for Google. Google sitemap is created in XML. If you have google sitemap in your site than google can easily crawl all the internal page links of your site. You can use the online tools that can create a XML based sitemap for google.

10.Robot.txt: -
When you do not want to crawl any file or image by search engine spiders than you can create robots.txt file and in that file you can mention the files, images which you don't want to crawl by the search engine spiders.

Best Wishes

Viral Bhatt

Tuesday, February 12, 2008

Page under constraction