16 replies
by mnf
I've got a strange error "OleDbException: Could not find file 'C:\WINNT\system32\ASWLocus'" when run SQL query for ACCESS database using System.Data.OleDb Data Provider in .Net code.
It was strange because the database I've tried to access was in the different directory and name also was different-
"C:\DataSamples\Locus.mdb" I've checked that it was specified correctly in the Connection String.
The reason for the error was that I've used MS SQL Query Analiser to debug the SQL Query and referred to the Access Database as the Linked server ASWLocus.
I had FROM clause in the SQL string
" from ASWLocus...LD_MATTER as MATTER"
and OleDb Data Provider interpreted ASWLocus as a reference to the external database and tried to find it.
It makes sense, but it wasn't obvious when the error was reported.
by mnf
I am using VS Web Setup Projects to update customer sites with new version of our application. For a long period it installed the web application without any problems and new version started to work immediately.
Relatively recently (from beginning of March 2005) more and more sites experienced problems immediately after installation of the new version and iisreset is required (in some cases uninstall and then re-install is required).
I do not blame changes in our installation, because the same .msi file was used since January till May on different sites and problems started to be noticed from March. Another issue with disabling Session State was reported also frm March. I suspect (not confirmed) that it is a result of .NET Framework 1.1 Service Pack 1 installations.
by mnf
I have an ASP.NET application that use WebDav Queries to do full-text search in MS Exchange e-mail and public folders.
The application was written and worked with Exchange 2000. Recently we replaced it with Exchange 2003 (as a part of Small Business Server").
When I tried to use the application against Exchange 2003, the following error was shown:
System.Net.WebException: The remote server returned an error: (440) Login Timeout.
I've tried to reproduce it on the development machine and the different error was shown:
Could not establish trust relationship with remote server.
Fortunately it was easily fixed by running Outlook Web Access and installing the exchange Server Certificate on the development machine.
After this I was able to reproduce the same (440) Login Timeout and after finding many links on Google
the MS KB Article http://support.microsoft.com/default.aspx?kbid=817379 pointed to change
settings of the Exchange virtual directory in Microsoft Internet Information Server (IIS).Exchange virtual directory was configured to accept only Secure Sockets Layer (SSL) connections.
The next error was : 501 (not implemented).
I followed MS KB article http://support.microsoft.com/?kbid=839744 and re-create the Exadmin virtual server.
The next error was:The remote server returned an error: (401) Unauthorized.
Even i had changed Exchange virtual directory settings to enable Integrated Windows authentication accordong to
MS KB 817379 before, it was disabled and I had to re-enable it again.
Hurray, no more errors but also no results back returned.
Of course, I should to configure Full-Text Indexing as described in HOW TO: Configure Full-Text Indexing on Mailbox Stores in Exchange 2003 MS KB 822932.
By the way, "How to Confirm That You Have Configured Full-Text Indexing Correctly" section of the article is not correct for Outlook 2003. I followed the instructions and received a valid list of messages back. However "Full-Text Index" wasn't created yet and WebDav full-text queries returned nothing.
Ok, after a few hours of re-populating of the indexes the full-text search start to work for my account.
But it still returned nothing for other user.
After a fair number of attempts I found that "full text" search works only if in Outlook 2003 "Use cached Exchange Mode" is specified. I didn't find that it is documented somewhere.
Now I can search e-mails, but for searching of public folders it returns "422 Unprocessable Entity".
It actually means that Full-Text Indexing is not enabled for public folders and I should repeat the same steps from HOW TO: Configure Full-Text Indexing on Mailbox Stores in Exchange 2003 but for Public Folders.
Is it a good exersize to just make working application to work again?
by mnf
I am having C# code converted from VB.net using Reflector and it's often uses StringType.FromObject to convert datarow column values to strings.
Recently I've got the error "Cast from type 'Guid' to type 'String' is not valid."
That's right, Microsoft.VisualBasic.CompilerServices.StringType.FromObject doesn't handle GUID type.
So I've created a helper function to extend StringType.FromObject.
//using Microsoft.VisualBasic.CompilerServices;
public static string StringFromObject(object Value)
{
string sRet=null;
if (Value!=null)
{
//special case for Guid because is is not supported by Microsoft.VisualBasic.CompilerServices.StringType.FromObject
if (Value.GetType()==typeof(Guid))
sRet= Value.ToString();
else
sRet=StringType.FromObject(Value);
}
return sRet;
}
by mnf
Our ASP.NET application use ASP.NET DataGrid control to allow in-line editing of the record. It uses text box Custom Columns developed using technique described in Creating Custom Columns for the ASP.NET Datagrid article.
However it was noticed that if value in the database is a string with NewLine characters, inline editing removes NewLine characters.
To workaround this it is required to in the DataBinding function of the control
check the value to show and change the type of the TextBox to "MultiLine" if required.
If oTextBox.Text.IndexOf(vbNewLine) >= 0 Then '
oTextBox.TextMode = TextBoxMode.MultiLine
End If
It solves the problem to keep new lines if they already exist in the field.
By default the edit text box is shown as single line and it is acceptable for fcolumns, that usually expects text without new lines. For columns that are usually have newLine characters, textMode should be changed to TextBoxMode.MultiLine unconditionally.
by mnf
I am using HtmlAgilityPack to parse html and retrieve metadata from the web pages.
Recently I noted that it doesn't correctly determine encoding of the web page.
The reason is that HtmlAgilityPack.HtmlWeb.Get method checks only ContentEncoding property which is extracted from http headers.
Unfortunately not all web servers use the same header to specify target character set.
The more accurate approach is described in Feroze Daud's blog
Also note that the code doesn't rely on HttpWebResponse.CharacterSet property. the property seems almost never populated correctly.
I've created the new class based on Feroze Daud's blog post and changed the HtmlAgilityPack.HtmlWeb.Get method to use the new class.
Update: Simon Mourier pointed me to existing method HtmlAgilityPack.HtmlDocument.DetectEncoding that simplifies the parse.
This is HttpResponseHelper class:
using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Diagnostics ;
using System.Net;
using System.Collections.Specialized;
using HtmlAgilityPack;
namespace FSHelperLib
{
using System;
using System.Text;
using System.Web;
/// <summary>
/// Summary description for HttpResponseHelper.
/// </summary>
public class HttpResponseHelper
{
// Methods
public HttpResponseHelper()
{
}
/// <summary>
/// Idea from http://blogs.msdn.com/feroze_daud/archive/2004/03/30/104440.aspx
/// If header ContentEncoding and CharacterSet are not specified use META HTTP-EQUIV
/// </summary>
/// <param name="resp">HttpWebResponse retrurned by req.GetResponse()</param>
/// <param name="strmMem">returns MemoryStream if it was populated when getting META HTTP-EQUIV
/// Parameter returns null if If the Content-Type header exists, and the value for this header contains a charset</param>
/// <returns>Detected Encoding or null</returns>
/// <remarks>Encoding can also be specified in the stream itself (using byte order mark)- not handled at the moment
///</remarks>
public static Encoding DetectEncoding(HttpWebResponse resp,out MemoryStream strmMem)
{
//bool bEncodingDefined=false;
strmMem=null;
Debug.WriteLine("The encoding method used is: " + resp.ContentEncoding);
Debug.WriteLine("The character set used is :" + resp.CharacterSet);
Encoding respenc = GetEncoding(resp.ContentEncoding,"ContentEncoding");
//if(respenc==null) respenc =GetEncoding(resp.CharacterSet ,"CharacterSet");
if(respenc==null) respenc =GetEncoding(GetCharsetFromContentType(resp),"CharsetFromContentType");
if(respenc==null)
{
Debug.WriteLine(NameValueCollectionAsString(resp.Headers,"response.Headers")) ;
respenc = GetEncodingFromMeta( resp,out strmMem);
}
PrintEncoding(respenc);
if(strmMem!=null)
{ //Points to the start of stream
strmMem.Seek(0,SeekOrigin.Begin);
}
return respenc;
}
private static Encoding GetEncodingFromMeta(WebResponse resp,out MemoryStream strmMem)
{
// save data to a memorystream
Stream rs = resp.GetResponseStream();
strmMem = StreamCloneToMemory(rs);
rs.Close();
//Parse and retreive <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=??" />
//Simon Mourier pointed me to existing method HtmlAgilityPack.HtmlDocument.DetectEncoding
//it is more reliable than parse in http://blogs.msdn.com/feroze_daud/archive/2004/03/30/104440.aspx
HtmlAgilityPack.HtmlDocument doc =new HtmlDocument();
System.Text.Encoding enc=doc.DetectEncoding(strmMem);
return enc;
}
private static Encoding GetEncoding(string encodingName,string SourceFieldName)
{
Encoding respenc = null;
if(!IsNullOrEmpty(encodingName))
{
try
{
respenc = Encoding.GetEncoding(encodingName);
// bEncodingDefined=true;
}
catch(Exception ee)
{
Debug.WriteLine("Exception: GetEncoding: " + SourceFieldName + " = " + encodingName +Environment.NewLine + ee.ToString());
}
}
return respenc;
}
private static void PrintEncoding(System.Text.Encoding enc)
{
if(enc!=null)
{
Debug.Write(" EncodingName=" + enc.EncodingName);
Debug.Write(" WebName =" + enc.WebName );
Debug.Write(" BodyName=" + enc.BodyName);
Debug.Write(" CodePage =" + enc.CodePage );
Debug.WriteLine(" HeaderName=" + enc.HeaderName);
}
else Debug.WriteLine (" Encoding is null" );
}
private static string GetCharsetFromContentType(HttpWebResponse resp)
{ //NOTE HttpWebResponse.CharacterSet property not alays returns a correct value
//because it also checks for some "MediaType" (see in Reflector)
// see if content length header has charset = value
//
String charset = null;
String ctype = resp.ContentType;// resp.Headers["content-type"];//resp.GetResponseHeader("Content-Type"))
Debug.WriteLine("Content-Type= " + ctype) ;
if(ctype != null)
{
int ind = ctype.IndexOf("charset=");
if(ind != -1)
{
charset = ctype.Substring(ind + 8);
Debug.WriteLine("Content-Type: charset=" + charset);
}
}
return charset ;
}
/// <summary>
/// Creates MemoryStream copy of stream provided
/// </summary>
/// <param name="rs">Source Stream will be positioned at the end when returned </param>
/// <returns>MemoryStream copy of the source Stream, position at the beginning</returns>
private static MemoryStream StreamCloneToMemory(Stream rs)
{
// save data to a memorystream
MemoryStream rawdata = new MemoryStream();
byte [] buffer = new byte[1024];
int read = rs.Read(buffer,0,buffer.Length);
while(read > 0)
{
rawdata.Write(buffer,0,read);
read = rs.Read(buffer,0,buffer.Length);
}
rawdata.Seek(0,SeekOrigin.Begin);
return rawdata;
}
#region FSHelperLib
//From TraceHelper
public static string NameValueCollectionAsString(NameValueCollection coll, string sComment /* = "" */)
{
string sRet = "";
if (sComment.Length > 0)
{
sRet += sComment+Environment.NewLine ;
}
int loop1, loop2;
// Get names of all keys into a string array.
String[] arr1 = coll.AllKeys;
for (loop1 = 0; loop1 < arr1.Length; loop1++)
{
sRet +=("Key: " + arr1[loop1] );//+Environment.NewLine;
String[] arr2=coll.GetValues(arr1[loop1]);
for (loop2 = 0; loop2 < arr2.Length; loop2++)
{
sRet +=(" Value " + loop2 + ": " + arr2[loop2] ) +Environment.NewLine;
}
}
return sRet;
}
public static bool IsNullOrEmpty(string oItemValue)
{
bool bRet = ((oItemValue == null)||(oItemValue.Length==0));
return bRet;
}
#endregion //FSHelperLib
}
}
The changes in the HtmlAgilityPack.HtmlWeb.Get method are in two places:
//MNF 22/5/2005 begin changes
MemoryStream strmMem=null; //MNF 22/5/2005
respenc =FSHelperLib.HttpResponseHelper.DetectEncoding(resp,out strmMem);
// if ((resp.ContentEncoding != null) && (resp.ContentEncoding.Length>0))
// {
// respenc = System.Text.Encoding.GetEncoding(resp.ContentEncoding);
// }
// else
// {
// respenc = null;
// }
//MNF 22/5/2005 end changes
and
//MNF 22/5/2005 begin changes
Stream s= resp.GetResponseStream();
Stream s ;
if (strmMem==null)
{
s= resp.GetResponseStream();
}
else
{
s=strmMem;
}
//MNF 22/5/2005 end changes
by mnf
Recently I've noticed that when user opens a report in the MS Access ADE application and use Print menu item from custom menu, the whole report is printed and no dialog box appears to selct printer and pages.
There is an TechRepublic article how to customise menu to show dialog in Word, but unfortunately I didn't find a way to do the same in MS Access XP. It seems not working in Access 2000 as well.
Fortunately if user has a report opened in Preview and clicks Control-P the desired Print Dialog box is shown and user can select pages to print.
by mnf
I had an error when tried to open the page http://www.lycos.com/ using HtmlAgilityPack from my ASP.NET application.
The exception was System.Net.WebException: The underlying connection was closed: The server committed an HTTP protocol violation.
When I tried to reproduce the problem using the test function GetLycosUrl (see below) from WinForms application, it throwed the different (403) forbidden error. After some research I found that HTTP protocol violation can be ignored, if you specify UseUnsafeHeaderParsing=true in the configuration file. HttpWebRequest.UseUnsafeHeaderParsing property is internal and read-only and can't be changed for particular instance of HttpWebRequest.
It is also suprising that WinForms application does not raise HTTP protocol violation error even the debugger shows that UseUnsafeHeaderParsing =false.
Now the question was why lycos send me back lycos send me back (403) forbidden error.
With the help of Fiddler I identified that the differense between IE and call from my application is UserAgent header. If header will be provided, valid page will be returned from HttpWebRequest.GetResponse.
To make HtmlAgilityPack more robust the change in HtmlWeb.Get(Uri uri, string method, string path, HtmlDocument doc) is required.
//MNF 26/5/2005 Some web servers (e.g. http://www.lycos.com/) return 403 forbidden error unless UserAgent is specified
//so let's say it's IE6
req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)";
//alternatively it can be changed in PreRequest event handler
The function to test www.lycos.com url is the following:
//Add using to the top of file
// using System.Net;
// using System.Diagnostics;
private void GetLycosUrl()
{
string url=@"http://www.lycos.com/";
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
//the following line is critical, otherwise (403) forbidden error error will be returned
request.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)";
try
{
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
}
catch (Exception exc)
{
Debug.Assert(false,exc.ToString());
throw;
}
}
by mnf
I am using Eric Woodruff 's ASP.NET Common Web Page Class Library to detect changes and prompt user if any changes are not saved.
There are a few modifications that I've done.
Even if I found that using SmartNavigation is not a good idea additional error handling in the JavaScript function BP_funCheckForChanges would not harm:
var oForm = document.forms[BP_strFormName];
try //MNF 4/8/2004 to avoid errors with SmartNavigation=true and page is moved away (eg Error message)
{ if (oForm.elements==null)
{ //debugger;
return;
}
}
catch(err)
{
return;
}
and
var ctlDirty = document.getElementsByName("BP_bIsDirty")[0];
if (ctlDirty==null) return;//MNF 9/3/2005 to avoid errors with SmartNavigation=true and page is moved away
I also extended the code to support inline editing in DataGrid. It's also required that Save/Update button will have non-standard attribute BypassPrompt="true".
//MNF 2/8/2004 added special case for datagrid buttons
//document.activeElement.outerHTML "<A href=\"javascript:{if (typeof(Page_ClientValidate) != 'function' || Page_ClientValidate()) __doPostBack('_ctl1$grd$_ctl3$_ctl0','')} \">
if(document.activeElement)
{
var oElem = document.activeElement;
if (oElem.tagName=="A")
{ if(oElem.parentElement.tagName=="TD")
{ if (oElem.children.length>0)
{ //Expected that Update image will have attribute BypassPrompt=="true"
if (oElem.children(0).BypassPrompt=="true") bPrompt = false;
}
}
}
}
//MNF 2/8/2004 end special case for datagrid buttons
Also I am using button's ClientIDs to generate BP_arrBypassList and it causes problems if the button belongs to user control.To avoid the problem, the following code was added to the
if(strID != "") block.
//If submit button belongs to sub-control the strID is likely to have colon in the name "_ctl0:btnImportFromDatabase"
//But if BP_arrBypassList is generated using Control.ClientID, the separator is '_'
//We have to replace all ':' to '_'
if (strID.indexOf(':') >= 0)
{
strID=strID.replace(':', '_');
}
by mnf
I am using my own functions to set Default Button on ASP.NET web form.
They were created based on Janus Kamp Hansen sample[^] and later using Darrell Norton's code [^].
I found that it's convinient to set the same Default Button to the container that will apply for all children- container can be WebControl or HtmlControl.
And recently I found that this approach required escaping for TextArea(otherwise Enter Key submits default button instead of entering new line in text box).
'overloaded methods for WebControl and HtmlControl are required because common parent class Control doesn't have Attributes property
Public Shared Sub DefaultButton(ByVal container As System.Web.UI.HtmlControls.HtmlControl, ByVal objDefaultButton As Control)
container.Attributes.Add("onkeydown", "DefaultButton('" & objDefaultButton.ClientID & "',event);")
container.Page.RegisterStartupScript("ForceDefaultToScript", DefaultButtonScript())
End Sub
Public Shared Sub DefaultButton(ByVal container As System.Web.UI.WebControls.WebControl, ByVal objDefaultButton As Control)
container.Attributes.Add("onkeydown", "DefaultButton('" & objDefaultButton.ClientID & "',event);")
container.Page.RegisterStartupScript("ForceDefaultToScript", DefaultButtonScript())
End Sub
'call if container has defaultButton but child (eg textarea) doesn't need it.
Public Shared Sub EscapeDefaultButton(ByRef ctrl As System.Web.UI.WebControls.WebControl)
'See also DefaultButton
ctrl.Attributes.Add("onkeydown", "NoDefaultButton(event);")
ctrl.Page.RegisterStartupScript("ForceDefaultToScript", DefaultButtonScript())
End Sub
Private Shared Function DefaultButtonScript()
'From http://dotnetjunkies.com/WebLog/darrell.norton/archive/2004/03/03/8374.aspx.
Return JScript(ResourceToString("DefaultButton.js"))
End Function
In this code I am using helper functions JScript and ResourceToString [^] to access embedded resources
JS function is stored in a separate file DefaultButton.js with "build Action"="embedded resource"
Michael
by mnf
I've seen many places where people use inline concatenation to create some JavaScript in ASP.NET VB
using String '&' operator or StringBuilder.Append.
The code is usually hard to read.
It's easier to save JavaScript fucntion code into a separate file with "build Action"="embedded resource" and use several reusable helper functions.
Public Shared Function StreamToString(ByVal strm As Stream) As String
If strm.CanSeek Then strm.Seek(0, SeekOrigin.Begin)
Dim myReader As New StreamReader(strm)
Dim sRet As String = myReader.ReadToEnd()
Return sRet
End Function
Public Shared Function ResourceToString(ByVal ResName As String) As String
' Get the current assembly.
Dim Asm As [Assembly] = [Assembly].GetExecutingAssembly()
Return ResourceToString(ResName, Asm) 'call overload
End Function
Public Shared Function ResourceToString(ByVal ResName As String, ByVal Asm As [Assembly]) As String
' Resources are named using a fully qualified name.
Dim sName As String = Asm.GetName().Name + "." + ResName
Dim strm As Stream = Asm.GetManifestResourceStream(sName)
' Read the contents of the embedded file.
If strm Is Nothing Then
Throw New ApplicationException("Couldn't find embedded resource " & sName)
End If
Dim sRet As String = StreamToString(strm)
Return sRet
End Function
Public Shared Function JScript(ByVal sScript As String)
Return "by mnf
My ASP.NET application used to send content of one page from another using HttpWebRequest similar to the following
Dim objResponse As HttpWebResponse
Dim objRequest As HttpWebRequest = System.Net.HttpWebRequest.Create(url)
objResponse = objRequest.GetResponse()
It worked fine, before I desided to use session object in the sending page.
I've created CookieContainer and passed sessionID, but it didn't work.
GetResponse waited for a while and returned time-out.
As I understand, ASP.Net serializes access to session and blocks re-entrance (fair enough) .
Fortunately, I found Eric Woodruff's article[^], that gave me the solution. Thanks again, Eric.
Michael
by mnf
I like to use SmartNavigation="true" option, but there are several problems with it.
Recently I put MetaBuilders.ComboBox[^] on the page with SmartNavigation="true" and found that after Postback ComboBox is shown as 2 different controls- text and dropdown list.
Reading source I found that rendered page has the following javascript for IE
window.attachEvent("onload", ComboBox_Init);
But the problem is that when SmartNavigation="true", postbacks do not cause onload events.
Thanks to ideas from Jim Fisher[^] and Fons Sonnemans [^] I've changed the code to the following
if(window.__smartNav!=null) //handle smartnavigation
{ window.setTimeout(ComboBox_Init,20);
}
else
{ window.attachEvent("onload", ComboBox_Init);
}
and now the ComboBox works correctly with SmartNavigation.
Michael
by mnf
I found that some functions with array of strings that may be useful, but they are not in framework classes.
If someone needs all strings in string array to be in low case, the following simple function can be useful.
public static string[] ToLower(string[] sArray)
{
for(int i=0;i<sArray.Length;i++)
{
sArray[i]=sArray[i].ToLower();
}
return sArray;
}
Michael
by mnf
I found that function Contains to check if field name exist in the record, is available for DataRow is missing for DataReader/IDataRecord.
So the following simple function can be useful.
public static bool Contains(IDataRecord row, string FieldName)
{
bool bRet=true;
try
{
row.GetOrdinal(FieldName);
}
catch //(Exception exc)
{
bRet=false;
}
return bRet;
}
Michael
by mnf
My current blog is located at http://geekswithblogs.net/mnf/[^]
Michael Freidgeim.
This discussion is closed to new replies.
Trending After Hours posts
Sort by Trending