Wednesday, December 29, 2010

Retrieving a hidden field in GridView control

The DataKeyNames field on the Gridview identifieds the field used for the value.
In processing, use the DataKey(index).value to retrieve the value






























As, you can see in the code above the DataKeyNames property is set to "TaskID" which, is the primary key in the table. Now, let's see how we can access all the TaskID of the rows which are checked using the CheckBoxes.

DataKey key;
foreach (GridViewRow row in gvInComplete.Rows)

{

bool result = ((CheckBox)row.FindControl("chkSelect")).Checked;

if (result)

{

key = gvInComplete.DataKeys[row.RowIndex];

Response.Write((int)key.Value);

}

}

Wednesday, December 22, 2010

Making modal dialog windows work in ASP.Net the easy way

Making modal dialog windows work in ASP.Net the easy way
Posted by raymondlewallen on December 9, 2005

Powered by WP Greet Box WordPress Plugin
This is an old solution to an old problem, but since somebody asked
me if I knew how to solve this problem, I thought I’d post the solution
here to make it easier for people to find in the future.

The problem has to do with ASP.Net and modal windows (windows opened
by parent windows using ‘window.showModalDialog()’). If you’ve ever
launched a modal window and issued a postback by clicking a button or
tried to redirect, you know that it always opens a brand new window,
and that is super annoying and unusable.

So, if you want to know how to use modal windows in Asp.Net and not
have them keep opening new windows, the solution (and I my friend will
can testify this simple solution works) does work. There are much more
elaborate solutions posted out on the internet, but trust me, its just
this easy, even though slightly inconvenient.

First, in the HEAD of EACH PAGE that will be as a modal window or called from a modal window, you have to have the following:
[code]


This name you give each page MUST be unique for each page.

Now, just set the target of the form in your page to target the name of the page the form exists on, like such:


With a completely new and blank page, the whole thing would look like this: <%@ Page Language=“VB” AutoEventWireup=“false” CodeFile=“Default.aspx.vb” Inherits=“_Default” %> Untitled Page
This entry was posted in .Net Development. Bookmark the permalink. Follow any comments here with the RSS feed for this post.


Also, adding this line in the head section will keep from spawning new windows:


<base target="_self">

[/code]

Tuesday, December 21, 2010

Call an aspx page from a vb class

Re: How to call an aspx page from a vb class?
You can pass the Request and Response objects from the ASPX page into the DLL. Then your DLL can use those objects.
Code:
Public Class MyWebHelper
Private m_Server As HttpServerUtility = Nothing
Private m_Request As HttpRequest = Nothing
Private m_Response As HttpResponse = Nothing

Public Sub New(server As HttpServerUtility, request As HttpRequest, response As HttpResponse)
m_Server = server
m_Request = request
m_Response = response
End Sub

Public Sub RedirectToLogin()
m_Response.Redirect("mylogin.aspx")
End Sub
End Class
In ASPX class:
Code:
Private Sub Page_Load(...)
If (Not IsLoggedIn) Then
Dim hlpr As New MyWebHelper(Server, Request, Response)
hlpr.RedirectToLogin()
End
End Sub

Private Function IsLoggedIn() As Boolean
' validate user
End Function
__________________
Good Luck,
-Cool Bizs

[Check out my free software site: Tutorials Hut]

#5
May 24th, 2005, 08:23 PM
subdigital
Member

Join Date: Jan 2004
Location: Houston
Posts: 54

Re: How to call an aspx page from a vb class?
no, that is completetly unnecessary.

If you can be sure that the code will be running withing a web request (ie, this class/method will not be used by any win forms code) then you can ALWAYS get access to the current request by doing this:

Code:
System.Web.HttpContext.Current
This will give you access to the Request/Response objects, as well as Session, Application, and cookies.

Sunday, December 19, 2010

Post XML Data to an ASP.NET Page using C#

By S Sansanwal | 18 May 2005
This article describes the function to post XML data to an ASP.NET page and then read the data on an ASP.NET page
19
Article Browse Code Stats Revisions
3.53 (23 votes)
Sponsored Links

See Also
Articles like this
Articles by this author
Code For Posting

To post XML, use the following function:

Collapse
WebRequest req = null;
WebResponse rsp = null;
try
{
string fileName = "C:\test.xml";
string uri = "http://localhost/PostXml/Default.aspx";
req = WebRequest.Create(uri);
//req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
req.Method = "POST"; // Post method
req.ContentType = "text/xml"; // content type
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
writer.WriteLine(this.GetTextFromXMLFile(fileName));
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse();

}
catch(WebException webEx)
{

}
catch(Exception ex)
{

}
finally
{
if(req != null) req.GetRequestStream().Close();
if(rsp != null) rsp.GetResponseStream().Close();
}Function to read xml data from local system
///
/// Read XML data from file
///

/// /// returns file content in XML string format
private string GetTextFromXMLFile(string file)
{
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}
Code For Reading Posted Data

Now, on the Web server in the ASP.NET page, write the following code to access the posted data:

Collapse
private void Page_Load(object sender, EventArgs e)
{
page.Response.ContentType = "text/xml";
// Read XML posted via HTTP
StreamReader reader = new StreamReader(page.Request.InputStream);
String xmlData = reader.ReadToEnd();
}
License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Using Returned XML with VB.NET

Once you have retrieved data from a web service you will need to do something with it. This HOWTO describes the various built-in methods .NET provides to use XML returned by a web service.
Overview
Returned Data to a String
Using XmlReader
Using XmlDocument
Using XPathNavigator/XPathDocument
Using a DataSet
Further Reading
Overview
The .NET Framework provides excellent support for XML. Combined with the databinding support of WinForms and ASP.NET applications you have an easy and powerful set of tools. ASP.NET 2.0 takes databinding another step further by providing the DataSource control which lets you declaratively provide data access to data-bound UI controls.
Returned Data to a String
The simplest way to view the returned data is to get the response stream and put it into a string. This is especially handy for debugging. The following code gets a web page and returns the contents as a string.
VB.NET STRING SAMPLE

Public Shared Function GetPageAsString(ByVal address As Uri) As String

Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Dim result As String

Try
' Create the web request
request = DirectCast(WebRequest.Create(address), HttpWebRequest)

' Get response
response = DirectCast(request.GetResponse(), HttpWebResponse)

' Get the response stream into a reader
reader = New StreamReader(response.GetResponseStream())

' Read the whole contents and return as a string
result = reader.ReadToEnd()
Finally
If Not response Is Nothing Then response.Close()
End Try

Return result

End Function
USING XMLREADER

XmlReader provides fast forward-only access to XML data. It also allows you to read data as simple-typed values rather than strings. XmlReader can load an XML document without having to use HttpRequest, though you won't have the same amount of control over the request. If you use HttpRequest, you can just pass the stream returned by the GetResponseStream() method to XmlReader. Fast write-only functions are provided by XmlTextWriter.
With .NET 2.0 you should create XmlReader instances using the System.Xml.XmlReader.Create method. For the sake of compatibility and clarity the next sample uses the .NET 1.1 creation method.
VB.NET XMLREADER SAMPLE

Imports System.Xml

' Retrieve XML document
Dim reader As XmlTextReader = New XmlTextReader( _
"http://xml.weather.yahoo.com/forecastrss?p=94704")

' Skip non-significant whitespace
reader.WhitespaceHandling = WhitespaceHandling.Significant

' Read nodes one at a time
While reader.Read()

' Print out info on node
Console.WriteLine("{0}: {1}", reader.NodeType.ToString(), reader.Name)

End While
USING XMLDOCUMENT

XmlDocument gives more flexibility and is a good choice if you need to navigate or modify the data via the DOM. It also works as a source for the XslTransform class allowing you to perform XSL transformations.
VB.NET XMLDOCUMENT SAMPLE

Dim doc As XmlDocument
Dim ns As XmlNamespaceManager
Dim nodes As XmlNodeList

' Create a new XmlDocument
doc = New XmlDocument()

' Load data
doc.Load("http://xml.weather.yahoo.com/forecastrss?p=94704")

' Set up namespace manager for XPath
ns = New XmlNamespaceManager(doc.NameTable)
ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0")

' Get forecast with XPath
nodes = doc.SelectNodes("/rss/channel/item/yweather:forecast", ns)

' You can also get elements based on their tag name and namespace,
' though this isn't recommended
'nodes = doc.GetElementsByTagName("forecast", _
' "http://xml.weather.yahoo.com/ns/rss/1.0")

For Each node As XmlNode In nodes
Console.WriteLine("{0}: {1}, {2}F - {3}F", _
node.Attributes("day").InnerText, _
node.Attributes("text").InnerText, _
node.Attributes("low").InnerText, _
node.Attributes("high").InnerText)
Next
Using XPathNavigator/XPathDocument
XPathDocument provides fast, read-only access to the contents of an XML document using XPath. Its usage is similar to using XPath with XmlDocument.
VB.NET XPATHDOCUMENT SAMPLE

Imports System.Xml.XPath

Dim doc As XPathDocument
Dim ns As XmlNamespaceManager
Dim navigator As XPathNavigator
Dim nodes As XPathNodeIterator
Dim node As XPathNavigator

' Create a new XmlDocument
doc = New XPathDocument("http://xml.weather.yahoo.com/forecastrss?p=94704")

' Create navigator
navigator = doc.CreateNavigator()

' Set up namespace manager for XPath
ns = New XmlNamespaceManager(navigator.NameTable)
ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0")

' Get forecast with XPath
nodes = navigator.Select("/rss/channel/item/yweather:forecast", ns)

While nodes.MoveNext()
node = nodes.Current

Console.WriteLine("{0}: {1}, {2}F - {3}F", _
node.GetAttribute("day", ns.DefaultNamespace), _
node.GetAttribute("text", ns.DefaultNamespace), _
node.GetAttribute("low", ns.DefaultNamespace), _
node.GetAttribute("high", ns.DefaultNamespace))
End While
Using a DataSet
Using a DataSet from the System.Data namespace lets you bind the returned data to controls and also access hierarchical data easily. A dataset can infer the structure automatically from XML, create corresponding tables and relationships between them and populate the tables just by calling ReadXml().
VB.NET DATASET SAMPLE

Imports System.Data

Public Shared Sub DataSetSample1()

Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim dsWeather As DataSet

Try
' Create the web request
request = DirectCast(WebRequest.Create( _
"http://xml.weather.yahoo.com/forecastrss?p=94704"), HttpWebRequest)

' Get response
response = DirectCast(request.GetResponse(), HttpWebResponse)

' Load data into a dataset
dsWeather = New DataSet()
dsWeather.ReadXml(response.GetResponseStream())

' Print dataset information
PrintDataSet(dsWeather)
Finally
If Not response Is Nothing Then response.Close()
End Try

End Sub

Public Shared Sub PrintDataSet(ByVal ds As DataSet)

' Print out all tables and their columns
For Each table As DataTable In ds.Tables
Console.WriteLine("TABLE '{0}'", table.TableName)
Console.WriteLine("Total # of rows: {0}", table.Rows.Count)
Console.WriteLine("---------------------------------------------------------------")

For Each column As DataColumn In table.Columns
Console.WriteLine("- {0} ({1})", column.ColumnName, column.DataType.ToString())
Next ' For Each column

Console.WriteLine(System.Environment.NewLine)
Next ' For Each table

' Print out table relations
For Each relation As DataRelation In ds.Relations
Console.WriteLine("RELATION: {0}", relation.RelationName)
Console.WriteLine("---------------------------------------------------------------")
Console.WriteLine("Parent: {0}", relation.ParentTable.TableName)
Console.WriteLine("Child: {0}", relation.ChildTable.TableName)
Console.WriteLine(System.Environment.NewLine)
Next ' For Each relation

End Sub

ending XML data in POST request

Sending XML data in POST request
How to create a POST request and send XML data
Posted on 12/18/2007 2:21:35 AM in #ASP.NET 2.X
Hi,

Many a times when we are working with the third party services we have to pass the data to the third party over the web. Most of the times we pass the data in the querystring. The data is passed in a get request along with the querystring. The third party takes the value from the querystring and process the data.

But many a times the data need to be passed in the Post method. Many a third party component takes the data in XML format in the POST request. In these cases we have to pass the data as XML string in the post request. Here is an example on how to pass XML in the post request.

string xml = “SomeXML Data”;

string url = @”http://www.vikramlakhotia.com/HomePage.aspx”;

WebRequest request = WebRequest.Create(url);

request.Method = "Post";

request.ContentType = "text/xml";

//The encoding might have to be chaged based on requirement

UTF8Encoding encoder = new UTF8Encoding();

byte[] data = encoder.GetBytes(xml); //postbody is plain string of xml

request.ContentLength = data.Length;

Stream reqStream = request.GetRequestStream();

reqStream.Write(data, 0, data.Length);

reqStream.Close();

System.Net.WebResponse response = request.GetResponse();

System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());

string str = reader.ReadToEnd();

That’s all you need to do to send XML in a post request.

Vikram


Share this post Email it
Feedback

Stamen
Posted on 10/5/2010 5:41:47 PM

Wednesday, October 6, 2010

NameValueCollection and .NET Configuration Files

I spent most of yesterday trying to figure out how to make use of a NameValueCollection in a .NET configuration file. After wasting almost the entire night fighting with this problem, I thought I would let everyone know that it is possible, and easier than you might think. (By the way, this was a clear case of working too long on the problem. After a good nights sleep, I solved this in under 5 minutes.)
At this point you might wonder why this was so difficult. The largest and most significant problem is the fact that NameValueCollection isn't serializable (KB 814187). The reason for this is that NameValueCollection doesn't implement ICollection but extends NameObjectCollectionBase instead. The recommended solution is to use a SoapFormatter to serialize and deserialize the collection. While using the SoapFormatter does work, it seemed like a very complex solution for a seemingly simple problem.
Not wanting to over-engineer my solution, I started searching the web for alternatives. I found several newsgroup postings that all said to use the SoapFormatter since that was the recommended solution and the only way to go. Not having drunk too much blue kool-aid, I kept searching. That search turned up an article by Keyvan Nayyeri that shows how to created a serializable NameValueCollection. This approach was intriguing and certainly seemed to be a more useful solution than using the SoapFormatter, but again it seemed like a lot of work.
Keep in mind, all I wanted to be able to do in the configuration file was to create a section that looked like this:
   1: <copyFiles>
   2:   <add name="C:\Windows" value="*.dll"/>
   3:   <add name="C:\Temp"/>
   4: </copyFiles>
Continuing the search, I thought I found my answer. I stumbled across an article (".NET How To Create and Use Custom Name-Value Config Sections") that shows how to do this in 4 simple steps. Reading through the article, I realized that it is written using the the .NET 1.0 and 1.1 ConfigurationSettings, which is provided for backwards compatibility only. Since the application I'm working on is .NET 3.5 and taking advantage of many of the new language features, I wanted to ensure that I wasn't using any deprecated classes.
This is where I started running into additional problems. It seems that Microsoft provides a NameValueSectionHandler, which the article makes us of. The problem is that NameValueSectionHandler is architected following the .NET 1.0/1.1 model and implements the System.Configuration.IConfigurationSectionHandler interface. This is great if you want to use the deprecated ConfigurationSettings class; if you want to use the recommended System.Configuration.ConfigurationManager or System.Web.Configuration.WebConfigurationManager classes you are out of luck. They will only work with a class that derives from ConfigurationSection.
So, after all this I thought I was out of luck and would need to write my own configuration section handler. (Remember, this was about 1:00 AM.) After sleeping on it, I realized that there was a much simpler way. Along with the NameValueSectionHandler, Microsoft also implemented NameValueConfigurationCollection and NameValueConfigurationElement, which derive from the appropriate configuration classes to be used by the ConfigurationManager. After seeing that, I realized that all I needed to do was implement a NameValueSection which derives from ConfigurationSection.
This is where the solution becomes easy. In it's simplest most form, the NameValueSection looks like this:
   1: public class NameValueSection : ConfigurationSection
   2: {
   3:     [ConfigurationProperty("", IsDefaultCollection = true)]
   4:     public NameValueConfigurationCollection Settings
   5:     {
   6:         get
   7:         {
   8:             return (NameValueConfigurationCollection)base[""];
   9:         }
  10:     }
  11: }
As you can see, this is pretty simple. In order to use it, you declare the section in your app.config file:
   1: <sectionGroup name="customSettings">
   2:    <section name="copyFiles" type="NameValueSection, CustomConfiguration"/>
   3: </sectionGroup>
   4: <copyFiles>
   5:    <add name="C:\Windows" value="*.dll"/>
   6:    <add name="C:\Temp"/>
   7: </copyFiles>
To access this configuration section in code, you simply need to do this:
   1: NameValueSection nameValueSection = ConfigurationManager.GetSection("copyFiles") as NameValueSection;
   2: if (nameValueSection != null)
   3: {
   4:     NameValueConfigurationCollection settings = nameValueSection.Settings;
   5:     foreach (string key in settings.AllKeys)
   6:     {
   7:         Console.WriteLine(settings[key].Name + ": " + settings[key].Value);
   8:     }
   9: }
This is about as simple as it gets. Even though you aren't actually using the real NameValueCollection you are using the NameValueConfigurationCollection, which has almost identical behavior. This is the solution that I finally ended up implementing and it works great. As you can see, with a minimal amount of effort you are now able to use a NameValueCollection in your configuration files.
posted on Sunday, March 16, 2008 8:00 PM



Click Here



Feedback



# re: NameValueCollection and .NET Configuration Files 4/30/2008 6:55 AM Sébastien Gillet
For the above sample to build I had to change the following (VS 2008):
1) encapsulate the copyFiles section into a customSettings section like:
<customSettings>
<copyFiles>
<add name="C:\Windows" value="*.dll"/>
<add name="C:\Temp"/>
</copyFiles>
</customSettings>

2) Also add this parent section into the GetSection call like in:
= ConfigurationManager.GetSection("customSettings/copyFiles")

# re: NameValueCollection and .NET Configuration Files 10/3/2008 5:16 PM Ben
when i ran above sample i got the error
"An error occurred creating the configuration section handler for customSettings/copyFiles: Could not load file or assembly 'CustomConfiguration' or one of its dependencies. The system cannot find the file specified." Any idea?

Thanks,

# re: NameValueCollection and .NET Configuration Files 11/15/2008 10:21 PM Scott
Ben, You need to ensure that System.Configuration is listed as a reference in your project.

# re: NameValueCollection and .NET Configuration Files 1/28/2009 11:03 AM UTCD
Why not use a custom AppSettingsSection?

<configSections>
<sectionGroup name="customSettings">
<section name="copyFiles" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</sectionGroup>
</configSections>
<customSettings>
<copyFiles>
<add key="C:\Windows" value="*.dll"/>
<add key="C:\Temp"/>
</copyFiles>
</customSettings>

NameValueCollection settings = ConfigurationManager.GetSection("customSettings/copyFiles") as NameValueCollection;
if (settings != null)
{
foreach (string key in settings.AllKeys)
{
Response.Write(key + ": " + settings[key] + "<br />");
}
}

# re: NameValueCollection and .NET Configuration Files 2/6/2009 10:33 AM Naresh
NameValueCollection settings = ConfigurationManager.GetSection("customSettings/copyFiles") as NameValueCollection;

I was using above logic and encountered an error "Cannot load the config file".

# re: NameValueCollection and .NET Configuration Files 11/22/2009 11:15 PM Jingle
Thank you! I have made it.

# re: NameValueCollection and .NET Configuration Files 4/30/2010 2:35 PM Rich Jardine
Scott,
Great solution! I am converting an app that uses extensive registry entries to use a custom config file. I couldn't access a NameValue Collection from the custom configuration until I found your solution.
Thank you!





Wednesday, September 1, 2010

If statements in Javascript must be enclosed in parentheses

  If statements in Javascript must be enclosed in parentheses and evaluation of the conditional stops once the condition can be ascertained as being either true or false. Thus all conditions may not be evaluated.

Also, the if statement can be written in shorthand

i.e.


value=(a==1) ? 1 : 0
which is equivalent to
if (a==1) then
    value=1;
else
    value=0;

Tuesday, August 31, 2010

Overriding a global var in a function in Javascript

  If you declare a variable in a function, it overrides a variable that is global.


That is, if you have

var mynum=1234;

function xyz()
{
   var mynum=34;
}

you have created a local variable.

Wednesday, August 25, 2010

CSS Classes and ID's

use the period in the CSS for class designation.
 Use the # for ID designation.

< p class=”BackgroundNote” > This paragraph contains an aside. < /p >

.BackgroundNote {}
Or you can create a selector that selects only the < p > elements that carry a class attribute with a value
of BackgroundNote (not other elements) like so:
p.BackgroundNote {}
If you have several elements that can all carry a class attribute with the same value (for example a < p >
element and a < div > element could both use the class attribute with the same value) and you want the
content of these elements to be displayed in the same manner, you will want to use the former notation.
If the styles you are defining are specific to just the < p > element whose class attribute has a value of
BackgroundNote , then you should use the latter notation.
A class attribute can also contain several values separated by a space — for example:
< p class=”important code” >



You can use the following syntax to indicate an element that has a class attribute whose value contains
both important and code (although IE7 was the first version of Internet Explorer to support this
syntax).
p.important.code {}
The ID Selector
The id selector works just like a class selector, but works on the value of id attributes. Rather than using a
period or full stop before the value of the id attribute, you use a hash or pound sign ( # ). So an element
with an id attribute whose value is abstract can be identified with this selector.
#abstract
Because the value of an id attribute should be unique within a document, this selector should apply
only to the content of one element (and you should not have to specify the element name).
The Child Selector
The child selector matches an element that is a direct child of another. In this case it matches any
< b > elements that are direct children of < td > elements. The names of the two elements are separated by a
greater - than symbol to indicate that b is a child of td ( > ) which is referred to as a combinator :
td > b {}
This would enable you to specify a different style for < b > elements that are direct children of the < td >
element compared with < b > elements that appear elsewhere in the document.
As a direct child of the < td > element, no other tags would sit between the opening < td > tag and the
< b > element. For example, the following selector does not make sense because the < b > element should
not be a direct child of a < table > element (instead, a < tr > element is more likely to be the direct child of
a < table > element):
table > b {}
IE7 was the first version of Internet Explorer to support the child selector.
The Descendant Selector
The descendant selector matches an element type that is a descendant of another specified element (or
nested inside another specified element), not just a direct child. While the greater - than symbol is the
combinator for the child selector, for the descendent selector the combinator is the space. Take a look at
this example:
table b {}
In this case, the selector matches any < b > element that is a child of the < table > element, which means it
would apply to < b > elements both in < td > and < th > elements.

Providers Web Blog

    This blog is used to document pertinent information used when creating web sites. Stuff such as javascript, html, css, etc.