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