The .NET Code Room
ASP.Net, VB.Net, C#, Microsoft Visual Studio .Net, Quick Tutorials, .Net Tips and Tricks, asp.Net Tips and Tricks, Ajay Sharma's Blog, Java Script, javascript, HTML, .Net Sample Codes
Monday, January 11, 2016
WCF service error: Service XYZ has zero application (non-infrastructure) endpoints.
Error:
System.ServiceModel.ServiceActivationException: The service XYZ cannot be activated due to an exception during compilation. The exception message is: Service 'XYZ' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.
Settings
Well, in my case the IIS site was running over https without any http binding. And web.config did have all the right settings e.g. endpoints, behaviors, ServiceMetadata httpGetEnabled="true" httpsGetEnabled="true" ....... and everything else.
Search
Now all my google searches indicated to verify the namespace in config and code but nothing worked for me.
Resolution:
As my website had only HTTPS binding defined in the IIS, I added a HTTP binding and things started working after that.
Tip: To add a http or https binding, open IIS, right click on website, choose BINDINGS option, then add required binding.
Also, other reasons for this error could be
1. Namespace issues in web.config and code
2. If ServiceMetadata option's httpGetEnabled or httpsGetEnabled are set to false.
Friday, August 30, 2013
Import dump file in SVN
Step 3: Create a new folder inside the new NewProjectRootName using repo-Browser
Step 4: Svnadmin load c:\Reposotories\NewProjectRootName < c:\Repositories\proj.dump
now command prompt will start dumping files to your filesystem, wait it to finish.
Friday, July 26, 2013
Insert Update Binary data in MS Sql Server
But If you need to insert/update or copy/paste the data which is already there in the database then it's not possible using the SSMS Table Editor (see attached image), it would give an error "The changed value in the call was not reognized as valid. .Net Framework Data Type: Byte[]
Error Message: You cannot use the Result pane to set this Field data to values other then null".
Solution
Use the SSMS Query editor to do this, i.e.
update TableName set BinaryColumnName = BinaryData
Entity Framework Function Import not returning Columns data
Reason
1) If the db procedure is using temporary table (e.g. #tempTable), EF don't recognize the MetaData from the procedure.
2) If multiple select ... statements exists in db procedure.
Solutions
Before executing procedure or beginning of db procedure set the FMTONLY to ON like below line:
SET FMTONLY ON
This will force EF to read the metadata from Temp tables
Disadvantage
There would be performance issues with approach because the way EF read the metadata from temp tables is to execute them multiple times.
Workaround
Instead of using the temp tables, create table variables and use them to store data temporarily. While using this option you don't need to set the FMTONLY setting.
Performance
Using the table variables will be faster than FMTONLY option.
Find more detailed information at
http://munishbansal.wordpress.com/2009/02/18/set-fmtonly-on-useful-in-tsql-ssis-packages-for-using-temp-tables/
Thanks
Sunday, June 12, 2011
Parameter is not valid. Asp.net GDI exception
I was getting this exception while working with the GDI images in asp.net.
My requirement was to upload the image from client then resize it and display.
The code was working fine on local development machine, but on production server it was throwing “Parameter is not valid” exception.
The general cause of this is that non-availability of resources required to generate a valid image file.
In my case the reason was that the destination folder was having read-only permissions, which was causing the code to hault while saving the processed image back to server.
For the resources I read during this issue, I found out some more reasons, these can be following:
1) Invalid source image path passed to the Drawing/Image/Bitmap object.
2) Invalid destination image path passed to the Drawing/Image/Bitmap object.
3) Corrupted/incomplete byte array.
4) Disposing of Source object before completing generation of new Image.
5) Folder write permissions while saving the new file.
Generic function to display images on webpage asp.net
Hi fellas,
I am writing this post after a long time. This new year I am back at blogging to help the software developers in writing better code .
Ever need of a generic/common function to display the images on website?
In normal practice, whenever we need to show an image, we used to directly write
Image.Src= “/userfiles/abc.jpg”;
This can be painful sometimes if your folder path gets changed, in that case you need to replace the folder (userfiles) everywhere.
Smart and better way is to create a common function that will display images. What you need to do is to call this method every time.
Method:
public string ShowImage(string ImageName)
{
string ReturnVal = string.Empty;
if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(“~/userfiles/” + ImageName)) == true)
{
ReturnVal = VirtualPathUtility.ToAbsolute(“~/userfiles/” + ImageName);
}
else
{
ReturnVal = VirtualPathUtility.ToAbsolute(“~/Images/ImageNotAvailable.jpg”);
}
return ReturnVal;
}
Usage:
imgThumbnail.ImageUrl = ShowImage(“abc.jpg”);
Explanation:
This method, takes a string parameter as image name to display. Then it checks that if the particular image exists or not.
If the image exists on the specified path then it returns the image name with full path (userfiles/abc.jpg) else it returns the alternate image path, which is imageNotAvailable.jpg.
This way if the image is not founded on server then user will be shown a imageNotAvailable.jpg
Thats it for now.
Sunday, May 23, 2010
goDaddy hosting, send emails using asp.net
I tried many options like ssl, default credentials, smtp, ports etc.
Finally below settings worked:
1) Setting From Email (abc@domainHostedOnGoDaddy.com)
2) SmtpClient as relay-hosting.secureserver.net
3) Disabling the SSL
4) Settings Credentials with username and password
Code
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
//set the addresses
mail.From = new System.Net.Mail.MailAddress("abc@domainHostedOnGoDaddy.com)","ABC");
mail.To.Add("recipientEMail");
//set the content
mail.Subject = "New Enquiry";
mail.IsBodyHtml = true;
mail.Body = "some message";
//set the smtp settings
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("relay-hosting.secureserver.net");
smtp.EnableSsl = false;
smtp.Credentials = new System.Net.NetworkCredential("abc@domainHostedOnGoDaddy.com","passwordofthisemail");
//send email
smtp.Send(mail);
lblMessage.Text = "email sent.";
Wednesday, February 10, 2010
Disable text selection and right click in html / asp.net pages
function disableselect(e)
function reEnable()
//if IE4+
//if NS6
body
{
-moz-user-select: none;
}
Sunday, October 4, 2009
this._form is null or not an object, JavaScript Error
this._form is null or not an object
Because of this error all my AJAX controls and page postback stopped working.
As the error clearly states that it is a JavaScript error so i started checking all my Javascript code.
Finally searching on the internet i found the cause and cure of this problem.
Cause:
If you are including javascript files in the page herader like the below:
<script src="aj.js" type="text/javascript" />
Solution:
Here the closing of script tag is not correct, through its an empty tag but somehow it needs to be closed as a old fashioned way, like done below:
<script src="aj.js" type="text/javascript"></script>
Close the javascript tag properly and see the magic yourself.
Wednesday, June 24, 2009
Read Excel files using C-Sharp windows application
using System.Data.OleDb;
private void btnRead_Click(object sender, EventArgs e)
{
try
{
string connStr = connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + @"\Courier.xls;Extended Properties=ImportMixedTypes=Text;Excel 8.0;HDR=Yes;IMEX=1;";
//You must use the $ after the object you reference in the spreadsheet
OleDbDataAdapter adap = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connStr);
DataSet ds = new DataSet();
adap.Fill(ds, "Courier");
dataGridView1.DataSource = ds.Tables["Courier"].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Explanation of the above code:
Here I used OleDb to read the excel file. The excel file resides with exe file as Courier.xls.
Sheet1$ is the name of excel sheet.
Courier is the name of file so i am using the same name in filling the DataSet.
Now at last the data is filled into dataGridView.
Now if you are not able to read the integer value or any value other then text then
include the
Extended Properties=ImportMixedTypes=Text;Excel 8.0;HDR=Yes;IMEX=1 property in connection string.
The above code can also be used in a web application, for this you need to replace the Application.StartupPath with Server.MapPath
HaPpY CoDiNg...........
Tuesday, June 23, 2009
URL rewriting using Global.asax, Error: The resource cannot be found.
The application is created in Asp.net, C# and MS Sql 2005.
The url rewriting logic was working on the my localhost but it didn't worked on production server.
I was getting an error: The resource cannot be found. while accessing the newly created URL pages.
I searched on Google about this and read lot, but nothing worked.
Finally I re-published the website and again uploaded all the files to production server and now everything worked like magic. Here is the URL: http://theplayclan.com/blog
Somewhere I read to check the permissions on server's IIS, this method is explained below:
1) Open IIS manager.
2) Right click on your website's virtual directory, select Properties.
3) Now, click on Configuration (in front of execute permissions option).
4) In the new popped-up window a list comes up as Application Extensions.
5) select .aspx option and click on edit.
6) Make sure that the Verify That File Exists is unchecked. This option explicitly check for the existence of file.
7) Save the settings and try again.
Somewhere it was mention to remove the *.* and regular expression extension mappings from the IIS may also work. The procedure of this is mentioned above.
Tuesday, March 24, 2009
Traverse / Loop through all form controls in asp.net
foreach (System.Web.UI.Control ctrl in this.form1.Controls)
{
//here your code
}
Further if you want to get the state or data or manipulate the control, use the below code:
Here I am checking that at least one DropDownList item is selected out of all DropDownLists in the current webform.
bool isSelected = false;
foreach (System.Web.UI.Control ctrl in this.form1.Controls)
{
if (ctrl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
{
DropDownList ddl = (DropDownList)ctrl;
if (ddl.SelectedItem.Text != “”)
{
isSelected = true;
break;
}
}
}
if (isSelected == true)
{
Response.Write(”selected”);
}
else
{
Response.Write(”none selected”);
}
Friday, January 9, 2009
Access your Asp.Net application over LAN
First of all you computer must be in the same workgroup as of the target computer. Then enter the following URL in the internet browser:
http://192.168.1.84/myWebsiteTest/default.aspx
or
http://ajay/myWebsiteTest/default.aspx
Here instead of ajay/192.168.1.84 you have to enter either the IP Address or the name of the computer on which asp.net application resides.
Just hit the enter key and you will see the output.
Happy Programing........
MyBase in VB.Net is equal to base in C#
So while using C# use "base" instead of "MyBase".
Happy Programing.
Saturday, November 15, 2008
Microsoft SQL Server DTS (Data Transformation Services) Import/Export Wizard Error
Error:
DTS Import/Export Error
Error Source: Microsoft OLD DB Provider for SQL Server
Error Description: [DBNETLIB][ConnectionOpen(Connect()).]SQL Server does not exist or access denied
Cause:
Inappropriate database drivers.
Solution:
In the Data Source combo-box
Select Microsoft ODBC Driver For SQL server
instead of
Microsoft OLE DB Provider For SQL server
Happy Programing.....
Thursday, November 6, 2008
Unable to validate data, ASP.net error
Unable to validate data, ASP.net error at System.Web.Configuration.MachineKeySection.GetDecodedData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Int32& dataLength) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
Information:
This is an View state decoding error.
Cause:
The basic reason of this is the difference of key while encrypting and decrypting the viewstate data. Suppose an asp.net rendered a page with key1 and saved the page state in view state, meanwhile asp.net’s key is changed to key2, now when some server side event will occur on page the viewstate will get decrypted and this error will occur as the old view state is now not valid due to a different encryption key.
It may occur when you open a page for along time and after that do some events on that.
Solution
Fix the key in your web.config file, so that only one key is used to encrypt and decrypt the viewstate data.
For more information visit:
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_21321364.html
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312906
Wednesday, October 15, 2008
Username Regex Validation
The validation can be done on server side and can also be done on client side.
Here I am explaining server side as this is the most secure way.
Althrough the client side validation is included in the source code
Click here to download visual studio solution code
Regex Code:
The Regular Expression below validates the username format.
^[a-zA-Z0-9_]{5,20}$
So while creating a new user for a website you can validate the username string with the following business logic:
1) User name must be between 5 to 20 characters.
2) User name can have lowercase and uppercase characters.
3) User name can be alpha-numeric.
4) No special character allowed.
Implementation:
Asp.net HTML code:<asp:TextBox ID=”txtRegex” runat=”server”></asp:TextBox>
<asp:Button ID=”btnValidate” runat=”server” Text=”Validate value” OnClick=”btnValidate_Click” />
<asp:Label ID=”lblResultRegex” runat=”server” Text=”"></asp:Label></div>
using System.Text.RegularExpressions;
protected void btnValidate_Click(object sender, EventArgs e){
if (Regex.IsMatch(txtRegex.Text, @”^[a-zA-Z0-9_]{3,16}$”) == true)
{
lblResultRegex.Text = “username ok”;
}
else
{
lblResultRegex.Text = “username invalid”;
}
}
Now just run the application an verify the results.
Click here to download visual studio solution code
Friday, October 10, 2008
Read & Write to System Registry data, keys using C#
In this post i am going to explain that how to access the System Registry and how to read and write data to registry.
Step 1: First you need to import the below namespaces:
using Microsoft.Win32;
Step 2: Now create an object of Registry class:
RegistryKey regkey;
Step 3: Now access the registry and get the value of a key
regkey = Registry.CurrentUser.CreateSubKey(@”Software\Microsoft\FTP”);
if (regkey.GetValue(”Use PASV”) == null)
{
txtValue.Text = “No Value Specified”;
}
else
{
txtValue.Text = regkey.GetValue(”Use PASV”).ToString();
}
The above code gets the value of the “Use PASV” key from the
Registry\CurrentUser\Software\Microsoft\FTP path.
Step 4: Set the key value
regkey.SetValue(”Use PASV”, txtValue.Text);
Monday, October 6, 2008
Website Design Guidelines / Checklist
2) Try to keep text and images separate. Avoid overlapping of separate elements.
3) Keep text content more than image.
4) Always use web fonts like: Arial, Helvetica, Times New Roman, Courier New / Courier so that design at execution won’t look different from raw file.
5) Put some textual content and links in bottom of every page (e.g. copyright, sitemap, ).
6) Usage of Headings is also good practice.
7) Avoid using lot of graphics or images that are hard to load, instead use a thumbnail to show and a new page (or popup) to view full image.
8) Headline plays a significant role in attracting customers. Hence use catchy phrases for the headline, it'll work well.
9) The most important is the content. Relevant content is the best way to keep the visitors hooked up and more over buy what you are selling. Correct use of words and sentences not only attracts the prospects but also helps the search engines to crawl it easily. Proper content, with relevant use of keywords is a MUST.
10) Determine the site navigation and its appearance before start designing. Also keep in mind we must use text as navigation, in case text is not possible images can be used but they must be small in size(kb), so that it wont take time to load.(Refer to yahoo home page).
11) User must should know where currently in site he is, show this by a textual bar like YOU ARE HERE
12) Avoid using gradient images in html page background, because it conflicts with site content and images at different screen resolutions.
13) Determine html link style (mouse over, normal) color and size.
Friday, October 3, 2008
How to get user’s IP address using asp.net
Many times we need to get the current user’s / visitor’s IP address.
Sometimes this is essential for security reasons.
We must leg the user’s IP address in the following situations:
1) where you accept data from user, like guestbook newsletter, search page etc. This gives a plus point to the security of website, as you can get the user’s identity by his IP if he do something wrong with your website.
2) User login pages. Alwayskeep record the logins of website users. Record the datetime and IP of user.
If you want to blok some particular users to use your website then on page load just ckeck the current Ip against database of ip’s you have created for blacklisting.
Now coming to the point,
How to get user’s IP address using asp.net
HttpContext.Current.Request.UserHostAddress;
or
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
The above code may return the IP with proxy.
Use the below code to get the IP address of the machine and not the proxy use the following codeHttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"
Monday, September 29, 2008
Preload images in HTML using JavaScript
A good example is of preloading in flash files, when you see a loader before displaying the content, and after loading site shows a smooth experience of flow of data.
This is mostly used when there is an mouser over images to be loaded. If user mouse overs an image and then you loads the new mouse-over image it may take a few seconds to load, which leads to a small blank image over the image area. By pre-loading the image you can show mouseover image instantly without any delay.In this post I am explaining how to do preaload imags in HTML using JavaScript, without using flash.
We have to use the Head tag of html as this is the one which loads on first page executiution.<head>
<script type=”text/JavaScript”>
{
pic1= new Image(190,53);
pic1.src=”images/productSmall.gif”;
pic2= new Image(190,53);
pic2.src=”images/storeSmall.gif”;
}
</head>
The above code lods two images naming productSmall.gif and storeSmall.gif respictively from images directory. It creates a new object of image and assigns it a dimention and a file to load.The document.imags condition has been used to determine that the browser supports the images or not.
Using RequiredFieldValidator with DropdownList Asp.Net
Step 2: Drag and RequiredFieldValidator. Set it’s ControlToValidate property to the DropDownLis’s object.
Step 3: Fill some items in the DropDownList. Add a first item as “Select”. This will indicate the user that he should select an option.Step 4: Now set the RequiredFieldValidator’s “InitialValue” property to “Select”.
Now all of your code should look like this :<asp:DropDownList ID=”cmbCountry” runat=”server”>
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>India</asp:ListItem>
<asp:ListItem>USA</asp:ListItem>
<asp:ListItem>Canada</asp:ListItem>
</asp:DropDownList>
Now you are all set to go and test it.
Click here to download Source code
Wednesday, September 24, 2008
Change MS SQL 2005 login password using sql query
sp_password ‘oldPassword’ , newPassword’
Note
Always use strong SQL passwords (i.e. having uppercase characters , lowercase characters, numeric values, special characters) for security purpose, this way it will be difficult to hack, hard to guess, hard to crack by brute force attacks.
Wednesday, September 17, 2008
Show line breakes in Asp.net Label
HTML formatted text contains “
” tags so while rendering the control .net framework handles the task to show the proper html formatted text into a Label.
Example:
lblDescription.Text=”name
description”;
The above code will display a line gap between name and description.
But in case if user inputted data using a non-HTML enabled TextBox then it is a point of problem.
While displaying data, inputted by simple multiline TextBox, line breaks looses its state and when the data displayed on a label it looks like a simple constant text line. Interestingly if you try to show the same data back in a TextBox it will look nice with proper line breaks. But we can’t use TextBox every where because of designing requirements.
To keep the line breaks you must convert the HTML new line special indicator to HTML break “
” tag.
Solution:
lblDescription.Text = txtInput.Text.ToString().Replace(Environment.NewLine, “<br>”);
The above code replaces the “NewLine” indications to “<br>” at run time, and displays the data same as input formatting.
Download Source Code
Friday, September 12, 2008
What is RSS feed
content format of text and related links.
Example:
I have a blog and you want to show the my Blog’s content on your website.
So what i have to do is to create a RSS of my blog content and give RSS generation page link to you.
The RSS page will generate an XML based on content I want to write in the file.
You have to consume that XML into your website and show the content.
These days nearly all blog websites provides their own RSS consuming applications, so you don’t have to bother about it if you are using a public web portal like orkut, WordPress, Blogspot etc.
Wait for a new post for reading and writing RSS applications.
Tuesday, September 9, 2008
Operator + cannot be applied to operands of type string and method group, C# error
This error comes up when you tries to append two strings with the “+” sign. As the + sign in C# is a arithmetical operator so you cannot use this too append two string type values. To use “+” the values or variables must be if numeric type.
As C# uses doesn’t supports implicit typecasting, for string concatenation use “&” sign.
Example
string varTest = "";
string str1 = "abc";
int str2=21;
varTest = str1 + str2;
The above stqatmet will cause in error stating "Operator + cannot be applied to operands of type string and method group". Because we are trying to add a string variable in a numeric variable.
To remove the error you must convert all the numeric (integer) datatype or variables to string.
varTest = str1 & str2.ToString();
The output of the above code will be abc21
Conclusion
We must convert all values to a uniform datatype before storing them into a variable.
Saturday, September 6, 2008
Send e-mail in ASp.Net 2.0 and onwards in C#
The Namespace of email class is changed to System.Net.Mail from System.Web.Mail.
Import the System.Net.Mail Namespace
using System.Net.Mail;
Code:
MailMessage mail = new MailMessage();
mail.From = new MailAddress(”info@yourDomain.com”,”Alert”);
mail.To.Add(”you@yourdomain.com”);
mail.Subject = “mail test”;
mail.IsBodyHtml = true;
mail.Body = “Your message here”;
SmtpClient smtp = new SmtpClient(”mail.yourdomain.com”);
smtp.Credentials = new System.Net.NetworkCredential(”info@yourdomain.com”,”password of this info”);
smtp.Send(mail);
Note:
The email address specified in the “FROM” field must be valid and it need to be of your domain.
In the SmtpServer the domain name must be same as of your domain on which website is hosted.
Click here to download full source-code for this post
Send e-mail using Asp.Net 1.1
First import Web.Mail namespace.
using System.Web.Mail;
Now add this code to your button click event:
MailMessage mail = new MailMessage();
String msgText = string.Empty;
msgText = “Message here, you can also use Html tags for Rich Text Formatting.
Hi.”;
mail.To = “you@yourdomain.com”;
mail.CC = “anyEmailAddress, its optional”;
mail.Bcc = “anyEmailAddress, its optional”;
mail.From = @”"”Ajay”"
//mail.From = “info@yourdomain.com”;
mail.Subject = “Mail test”;
mail.BodyFormat = MailFormat.Html;
mail.Body = msgText;
SmtpMail.SmtpServer = “mail.yourdomain.com”;
SmtpMail.Send(mail);
Note:
The email address specified in the “FROM” field must be valid and it need to be of your domain.
In the SmtpServer the domain name must be same as of your domain on which website is hosted.
Wednesday, September 3, 2008
Google’s Web Browser called Google Chrome is launched
Google has launched it’s own web browser named Google Chrome.
Google Chrome is a very simple and sophisticated browser and very easy yo use.
Google Chrome Features:
~ Multiple tabs can be opened in same instance window.
~ Thumbnails of most visited pages.
~ Automatic bookmarks and history search reaults when you type any URL.
~ Import settings and bookmarks from other web browsers.
~ Application shortcuts
~ Dynamic tabs
~ Crash control
~ Incognito mode
~ Safe browsing
~ Instant bookmarks
~ Simpler downloads
For more features visit http://www.google.com/chrome/intl/en-GB/features.html
Download Google Chrome here http://www.google.com/chrome/
So go and give a try to Google Chrome.
Monday, September 1, 2008
Rename a table Column in MS SQL
You can rename a column regardless of it is null or contains any data.
We need to use a System stored procedure to rename. Any command with alter keywords won’t work.
Code
EXEC sp_rename ‘tableName.[oldColumnName]‘, ‘newColumnName’, ‘COLUMN’
Example:
EXEC sp_rename ‘Ultra_tblPressRelease.[uShowStatus]‘, ‘uShowInA2B’, ‘COLUMN’
The above line will rename the existing column named uShowStatus of table tblPressRelease to uShowInA2B.
There will be no adverse effect of this procedure on your table data.
But you have to update all your SQL Cursors and Stored Procedures with the new column name (if any).
Saturday, August 30, 2008
ASp.Net 2.0 GridView Delete Button Confirmation pop-up
Instead of doing so much hardwork you can achieve this on the same page with a little bit of extra code.
Workaround
Add a client alert script to the delete button of every row.
In the delete event of GridView delete the record.
Download Source Code here
Code
==================================================
Page's Aspx Design File Begins
==================================================
<asp:GridView ID="gvFaq" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" OnRowDataBound="gvFaq_RowDataBound" OnRowDeleting="gvFaq_RowDeleting">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="slno" HeaderText="Sl No." />
<asp:BoundField DataField="cHeading" HeaderText="Question" />
<asp:BoundField DataField="cPosition" HeaderText="Position" />
<asp:CommandField HeaderText="Manage" ShowSelectButton="True" />
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
==================================================
Page's Aspx Design File Ends
==================================================
Database Design FIle
==================================================
Code Behind File Begins
==================================================
1) Import Namespaces
using System.Data.SqlClient;
2) Declare global variables which will be used in page
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = "your database connection string goes here"';
String sql = string.Empty;
3) Page Load event
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
fillGridView();
}
}
4) GridView filling method
private void fillGridView()
{
try
{
myConnection = new SqlConnection(connStr);
sql = "select * from tblFaq order by slno desc";
da = new SqlDataAdapter(sql, myConnection);
ds.Clear();
da.Fill(ds, "tblFaq");
gvFaq.DataSource = ds.Tables[0];
Page.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
5) In the RowDataBound event add a java script event to the delete cell.
protected void gvFaq_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[4].Attributes.Add("onClick", "return confirm('Are you sure you want to delete the record?');");
}
}
6) Handle the RowDeleting event to delete the record of current row.
protected void gvFaq_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
myConnection = new SqlConnection(connStr);
myConnection.Open();
sql = "delete from tblFaq where slno = " + Convert.ToInt32(gvFaq.Rows[e.RowIndex].Cells[0].Text);
SqlCommand oldcom = new SqlCommand(sql, myConnection);
oldcom.ExecuteNonQuery();
myConnection.Close();
fillGridView();
Response.Write("Record Deleted");
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
==================================================
Code Behind File Ends
==================================================
The output will look like this
javascript:void(0)
Download Source Code here
Monday, August 25, 2008
Show Message Box in Asp.net
But this can be achieved by generating a client side Java Script code in a server-side event.
Code
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
showMsg(”hey there”, Me)
End Sub
Public Sub showMsg(ByVal sMsg As String, ByVal frm As Web.UI.Page)
Dim sb As New System.Text.StringBuilder
Dim oFormObject As System.Web.UI.Control
sMsg = sMsg.Replace(”‘”, “\’”)
sMsg = sMsg.Replace(Chr(34), “\” & Chr(34))
sMsg = sMsg.Replace(vbCrLf, “\n”)
sMsg = “”
sb = New System.Text.StringBuilder
sb.Append(sMsg)
For Each oFormObject In frm.Controls
If TypeOf oFormObject Is HtmlForm Then
Exit For
End If
Next
oFormObject.Controls.AddAt(oFormObject.Controls.Count, New LiteralControl(sb.ToString()))
End Sub
Explanation:
On the button click event i write a JavaScript method to the page, the JavaScript method is displaying the message your pass to the method showMsg().
Note:
Please don’t pass special characters as the message, as they will conflict with the special characters of JavaScript and message won’t come properly.
Remove yellow autocomplete textbox background caused by Google Toolbar in Internet Explorer
Recently i ran into this problem, some users of my client’s website complaint that in some web forms the name and email fields comes have a yellow background which hinders the readability of the field.
After getting into depth details of the problem I came to knew that it happens only in Internet Explorer having Google Toolbar installed. In Firefox, Opera, Netscape it works fine.
This is a feature of Google Toolbar that it automatically highlights the fields (e.g. name, email etc.) in the yellow background color which facilitate the user to autocomplete the specified field.
Using some server-side and client side tweaks you can restrict the field to become autocomplete but Google Toolbar will still show the yellow background. The Google Toolbar feature overrides nearly all the server-side as well as client-side tweaks for the Name and Email fields.
Workaround:
To avoid the field’s autocomplete:
You can set the AutoCompleteType property in the Html tag of Textbox like:
<asp:TextBox ID=”txtemail” runat=”server” AutoCompleteType=”Disabled” Width=”219px”></asp:TextBox>
Some enumerations for the AutoCompleteType property are :
BusinessCity - City in the business category
BusinessCountryRegion - Country/region in the business category
BusinessFax - Fax number in the business category
BusinessPhone - Phone number in the business category
BusinessState - State in the business category
BusinessStreetAddress - Street address in the business category
BusinessUrl - Web site URL in the business category
BusinessZipCode - ZIP code in the business category
Cellular - Phone number in the mobile-phone category
Company - Business name in the business category
Department - Department in the business category
Disabled - AutoComplete feature is disabled
DisplayName - Name to display in the user category
Email - E-mail in the user category
FirstName - First name in the user category
Gender - Gender in the user category
HomeCity - Home city in the user category
HomeCountryRegion - Home country/region in the user category
HomeFax - Fax number in the user category
Homepage - Web site URL in the user category
HomePhone - Phone number in the user category
HomeState - Home state in the user category
HomeStreetAddress - Home street in the user category
HomeZipCode - ZIP code in the user category
JobTitle - Job title in the user category
LastName - Last name in the user category
MiddleName - Middle name in the user category
None - No category specified
Notes - Extra information in the form
Office - Office location in the business category
Pager - Phone number in the pager category
Search - Keywords in the search category
Please note the difference between None and Disabled enumerations.
But setting the AutoCompleteType property will only direct browser to not to give options for autocomplete, it doesn’t removers yellow background.
Remove Yellow background
Any code used to set the background color of textbox will fail in following conditions (regardless of run time or design time):
a) Specifying BackColor
b) Specifying background-color in CSS or Style attribute.
The one and only perfect way to do is :
a) Specify a CSS class for the textbox, e.g.
.txtNameStyle
{
font-size:12px;
height:13px;
border-style:none;
background-color: #666666 !important;
color:#ffffff;
}
b) Now declare the text box control so that it looks like this :
<asp:TextBox ID=”txtName” runat=”server” CssClass=”txtNameStyle” Width=”219px”></asp:TextBox>
Note:
The if the background is !important in Css-Style, the input is not considered by Google Toolbar. That’s all what we need.
Now the last step is to just test the page into Internet Explorer.
That’s all for this post, hope you will like it.
Please leave a comment for any help.
BYE
Friday, August 22, 2008
Update database data using SQL Cursors based on conditions
Hacker put some JavaScript code in all row data to get hits on his website (which is apparently blocked, and soon my site will also be got banned if it keep happening for a long time).
Because the database has a huge amount of data, i can’t update table data using ExecuteNonQuery commands as it will result in a great overload on database and network resources.
So I decided to make something logical which is fast and logical way to handle this situation, and at last i ended up with writing a cursor.
This cursor finds a specific string and replaces it with null.
Scenario:
Create a table with sample data
create table tblDataUpdateTest
(
slno int identity(1,1),
cName varchar(50),
cRemarks varchar(50),
)
insert into tblDataUpdateTest (cName, cRemarks) values (’name1′,’some text here BADCODE’)
insert into tblDataUpdateTest (cName, cRemarks) values (’name2′,’raBADCODEhul’)
insert into tblDataUpdateTest (cName, cRemarks) values (’name3′,’dj BADCODEis devil’)
select * from tblDataUpdateTest
Create Cursor to update database table
Declare @@counter int
set @@counter=0
Declare @@slno int
Declare @@cRemarks varchar(100)
Declare tmepTbl cursor
For
Select slno,cRemarks from tblDataUpdateTest
Open tmepTbl /* Opening the cursor */
fetch next from tmepTbl
into @@slno,@@cRemarks
while @@fetch_Status-1
begin
Update tblDataUpdateTest
set cRemarks = Replace(@@cRemarks,’BADCODE’,”)
where slno = @@slno
fetch next from tmepTbl
into @@slno, @@cRemarks
set @@counter=@@counter+1
end
close tmepTbl
Deallocate tmepTbl
Conclusion:
By running this cursor all the occurrences of BADCODE will be eliminated from the specified table.
Note:
I used word BADCODE here but in my actual data it was a java script tag which was creating all the problem.
Tuesday, August 12, 2008
Change fore color of control using Java Script
This can be achieved using CSS (supposing all of you know that) also but we can also do it using Java Script.
This is a simple java script trick so you can use it with html controls as well as asp.net server controls.
Here is an example for doing this :
Code:
<a href=”contact.aspx” class=”mainMenuNormalStyle” onmouseover=”style.color=’#FFB537′;”
onmouseout=”style.color=’#6D6E71′”>CONTACT</a>
<a href=”contact.aspx” class=”mainMenuNormalStyle” onmouseover=”style.backgroundcolor=’#FFB537′;”
onmouseout=”style.backgroundcolor=’#6D6E71′”>CONTACT</a>
In the above code example i set the value of style collection’s color property on the “onmouseover” event and reversed on “onmouseout” event.
Wednesday, July 30, 2008
XML Serialization in .Net Framework (Write Xml from Dataset)
Serialization is converting an object to a format in which it can be saved (exported) as file or a physical medium. A simple and basic example would be, if we create an XML from a Dataset it is called Serialization.
CODE:
try
{
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ToString();
SqlConnection myConnection = new SqlConnection(connStr);
String sql = "select * from tblCategory";
da = new SqlDataAdapter(sql, myConnection);
ds.Clear();
da.Fill(ds, "tblCategory");
ds.WriteXml(Server.MapPath("~/xmls/info.xml"));
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
The above code will write an XML file called info.xml from a Dataset called "ds" into xmls folder in root of website.
Options
Alternatively we can use some advanced options to format the data which is being written.
ds.WriteXml(Server.MapPath("~/xmls/info.xml", XmlWriteMode.WriteSchema);
Some options are. Some of the attributes available in Microsoft .Net Framework are as follows:
♣ XmlWriteMode.DiffGram — Writes the entire DataSet as a DiffGram.
♣ XmlWriteMode.IgnoreSchema — Writes the current contents of the DataSet as XML data, without an XML Schema Definition language (XSD) schema.
♣ XmlWriteMode.WriteSchema — Writes the current contents of the DataSet as XML data with the relational structure as inline XSD schema.
Saturday, June 21, 2008
Add meta tags to master page from content page Asp.Net
Step1
Put one content place holder in your master page in HEAD section, like::
<head id="Head1" runat="server">
<asp:ContentPlaceHolder runat="server" id="ContentHeaders"></asp:ContentPlaceHolder>
</head>
Step2
Now in the content (child) page, put this code:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentHeaders" runat="server">
<TITLE><%=pageTitle%></TITLE>
<META name="keywords" content="<%=varKeywords%>">
<META name="description" content="<%=varDescription%>">
</asp:Content>
Step3
In content page's vb or cs file code:
Declare variables as below in the global declaration section (not in page load)
Protected pageTitle As String = ""
Protected varKeywords As String = ""
Protected varDescription As String = ""
Step4
Fill values in page_load event:
pageTitle = "Your Meta Tag "
varKeywords = "Your Meta Tag "
varDescription = "Your Meta Tag "
Disable the right click on a web page
Some website has right-click disabled so that user cant copy paste using mouse, or cant save images contained into webpage.
Copy paste this code
<body oncontextmenu=”return false;”>
Html page content here
</body>
**End of article**
Wednesday, June 18, 2008
Rotate a Label Text
<asp:Label id="lblTotate" style="writing-mode:tb-rl" runat="server">your text here</asp:Label>
For more reference:
http://www.w3.org/TR/2001/WD-css3-text-20010517/
http://msdn.microsoft.com/en-us/library/ms531187.aspx
Friday, January 18, 2008
Read CSV into an Array
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
reader = My.Computer.FileSystem.OpenTextFieldParser _
("C:\Temp\test.csv")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
Dim currentRow As String()
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
Tuesday, January 15, 2008
Update dataset data back to database
The DataSet can be considered an in-memory cache of data retrieved from a database. The DataSet consists of a collection of tables, relationships, and constraints.
Firstly, we have to fill data into a DataSet from Database.
Secondly, when the DataSet is loaded, you can modify the data, and the DataSet will keep track of the changes made bu user.
The Add method of DataTable accepts either an array of the expected data columns, or a DataRow.
(Please note that all code is in c# language)
Step 1: Create a new Connection and SqlDataAdapter
SqlConnection myConnection = new SqlConnection("connectionStringGoesHere");
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("Select * from tblNews", myConnection);
DataSet myDataSet = new DataSet();
DataRow myDataRow;
Step 2: Create SqlCommandBuilder(The SqlDataAdapter does not automatically generate the Transact-SQL statements required to match changes made to a DataSet with SQL Server. But, you can create a SqlCommandBuilder object to automatically generate Transact-SQL statements for single-table updates.)
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
mySqlDataAdapter.Fill(myDataSet, "tblNews");
Step 3: Add rows to DataTable
myDataRow = myDataSet.Tables["tblNews"].NewRow();
myDataRow["cNewsId"] = "NewID";
myDataRow["cHeading"] = "New Heading";
myDataRow["cContent"] = "Content here";
myDataSet.Tables["tblNews"].Rows.Add(myDataRow);
Step 4: Editing Row Data
We can change the data in a DataRow by accessing the DataRow. Use the index of the row in the RowsCollection accessed through the Rows property:
myDataSet.Tables["tblNews"].Rows[0]["cHeading"]="Abc";
Access a specific row by specifying the Primary Key value:
DataRow myDataRow1 = myDataSet.Tables["tblNews"].Rows.Find("124");
myDataRow1["cHeading"]="Abc";
Here "124" is the value of the Primary Key "cHeading" in the "tblNews" table.
Step 5: Deleting a record
Use Delete method to delete a Row. All changes are done in dataset until you don't explicitly update DataSet data to the Database. Use RejectChanges method of DataSet to reverse all changes made to DataSet.
myDataSet.Tables["tblNews"].Rows[0].Delete();
Note: The original and new values are maintained in the row. The RowChanging event allows you to access both original and new values to decide whether you want the edit to proceed.
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
Step 6: Finally Update DataBase
To submit the data from the DataSet into the database, use dataAdapter's Update method.
mySqlDataAdapter.Update(myDataSet, "tblNews");
A Visual Studio Solution code sample will be coming soon......
Monday, January 14, 2008
Show default Text in Email Field
Show default Text in Email Field.
Like on form load show "enter email id" in email field.
On click clear this text.
on mouse out with nothing entered show again this into textbox.
Demo:
CODE::
Code:
<body><input type="text" name="email" value="Your e-mail adress" onfocus="if(this.value=='Your e-mail adress') this.value=''" onblur="if(this.value=='' ) this.value='Your e-mail adress';" />