Wednesday, November 12, 2008

Loop through files in a directory

The following example shows you how to programme path in ASP.NET:


Imports System.IO


Partial Public Class WebForm1


Inherits System.Web.UI.Page


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


'Note: TestPath is configured the root folder in IIS


Print("-------Path------------")


Print(Server.MapPath("~")) 'Root folder: C:\ALL\Dev\TestPath\


Print(Server.MapPath("~/")) 'Root folder: C:\ALL\Dev\TestPath\


Print(Server.MapPath(".")) 'Current folder: C:\ALL\Dev\TestPath\Folder1\Folder2


Print(Server.MapPath("..")) 'Upper-level folder: C:\ALL\Dev\TestPath\Folder1


Print(Server.MapPath("../..")) 'Upper-upper-level folder: C:\ALL\Dev\TestPath


Print("--------URL-----------")


Print(Request.RawUrl()) '/TestPath/Folder1/Folder2/WebForm1.aspx


Print(Request.PhysicalPath) 'C:\ALL\Dev\TestPath\Folder1\Folder2\WebForm1.aspx


Print(Request.PhysicalApplicationPath) 'C:\ALL\Dev\TestPath\


Print(Request.Url.AbsolutePath) '/TestPath/Folder1/Folder2/WebForm1.aspx


Print(Request.Url.LocalPath) '/TestPath/Folder1/Folder2/WebForm1.aspx


Print("--------File/Folder-----------")


Print(GetCurrentPageName) 'WebForm1.aspx


Print(GetFileExtension(Request.PhysicalPath)) '.aspx


Print(GetFileExtension1(Request.PhysicalPath)) '.aspx


Print(IsFileExist(Request.PhysicalPath)) 'True


Print(IsFolderExist(Server.MapPath(".."))) 'True


Print(IsFolderExist1(Server.MapPath(".."))) 'True


Print(FindFile(Server.MapPath("."), "form1")) 'WebForm1.aspx


End Sub


Private Sub Print(ByVal val As String)


Response.Write(val + "<br>")


End Sub


Public Function GetCurrentPageName() As String


Dim path As String = System.Web.HttpContext.Current.Request.Url.AbsolutePath


Dim file As New System.IO.FileInfo(path)


Return file.Name


End Function


Private Function GetFileExtension(ByVal path As String) As String


Dim file As New System.IO.FileInfo(path)


Return file.Extension


End Function


Private Function GetFileExtension1(ByVal path As String) As String


Return System.IO.Path.GetExtension(path)


End Function



Public Shared Function GetFileExtension2(ByVal filename As String) As String


Dim index As Integer = filename.LastIndexOf(".")


Return filename.Substring(index + 1, filename.Length - index - 1)


End Function


Private Function IsFileExist(ByVal path As String) As Boolean


Return File.Exists(path)


End Function


Private Function IsFolderExist(ByVal folder As String) As Boolean


Return Directory.Exists(folder)


End Function


Private Function IsFolderExist1(ByVal folder As String) As Boolean


Return My.Computer.FileSystem.DirectoryExists(folder)


End Function


Private Function FindFile(ByVal path As String, ByVal contains As String) As String


Dim wildcards As String() = {"*.jpg", "*.jpeg", "*.gif", "*.aspx"}


Dim Files As System.Collections.ObjectModel.ReadOnlyCollection(Of String) _


= My.Computer.FileSystem.GetFiles(path, FileIO.SearchOption.SearchTopLevelOnly, wildcards)


For Each f In Files


If f.IndexOf(contains, StringComparison.CurrentCultureIgnoreCase) >= 0 Then


Return System.IO.Path.GetFileName(f)


End If


Next


Return "Not Found"


End Function


End Class

Sunday, November 2, 2008

Loop through properties of a .NET Class

You could use reflection to return all the public properties of a current class, such as the name and value of the property.

Sample Code:

Imports System.Web


Imports System.Reflection


Partial Class HCNLogin


Private Sub CreateHCNCookies(ByVal userID As Integer)


If Request.Browser.Cookies Then


Dim hcnUser As HCNUser = hcnUser.GetByID(userID)


If hcnUser IsNot Nothing Then


Dim t As Type = hcnUser.GetType()


For Each p As PropertyInfo In t.GetProperties()


If Not p.Name.Equals("ID") AndAlso Not p.Name.Equals("intUserID") Then


Response.Cookies(p.Name).Value = p.GetValue(hcnUser, Nothing)


Response.Cookies(p.Name).Expires = DateTime.Now.AddYears(10)


End If


Next


End If


End If


End Sub


End Class


Reference:
Loop through object properties?

Running custom HttpHandler in IIS 7

  • When I am using a custom HttpModule/HttpHandler in IIS 7 under Vista, the handler does not fire. The fix is to change the application in IIS to the "Classic .NET AppPool". You can also use the DefaulAppPool by changing the web.config, refer to the references.
  • Also, IIS7 on Vista Client doesn't currently supports ASP.NET substitution caching while running in integrated mode. If you change it to classic mode it does.


References:

Using HttpModules and HttpHandlers under IIS7

HttpModule and HttpHandler sections in IIS 7 web.config files

IIS 7 Apppool "integrated" fails with ASP.NET Substitution

LINQ Connection String - app.config vs web.config

  • When you are using Linq to SQL, if you have your dbml in a class library project and you drag and drop a database table from the Server Explorer onto the dbml designer, VS2008 will automatically create the app.config for you which contains the connectionstring.
  • If you have a web application project which references the Linq class library and you want to put the connectionstring in the web.config, here is how:

1. Remove the default constructor in the dbml designer class. Create a partial class for the datacontext class which contains the constructor to re-set the connectionstring.

2. You need to set the dbml's connection to none whenever new stuff has been dragged onto the design surface.

3. Put the connectionstring in the web.config

Sample Code:

Imports System.Configuration


'We don't want to use app.config to store connectionstring, we need to use web.config


'So we need to set the dbml's connection to none whenever new stuff has been dragged onto the design surface


Partial Public Class MyDataContext


Public Sub New()


MyBase.New(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString, mappingSource)


End Sub


End Class

References:

How to set the connection string in your LINQ dbml file dynamically (based on web.config)

LINQ and Web Application Connection Strings

Importing Excel - Truncates at 255 characters

When you importing an excel file into database, if you are using OLEDB, the text being read from each cell will be truncated at 255 characters.

Solutions:
  • HKEY_LOCAL_MACHINE\Software\Microsoft\Jet\4.0\Engines\Excel\TypeGuessRows was set to 1. You can change it to a larger value and it now work.
  • You might consider using ODBC instead of OLEDB.

Sample code:

Imports System.Data.OleDb


Imports System.Data.Odbc


Module ImportExcel


Sub Main()


DoJob1()


End Sub


'Private Function GetData() As OleDbDataReader


' Dim cnAdo As New OleDbConnection()


' Dim cmCommand As New OleDbCommand()


' Try


' cnAdo.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=YES';Data Source=E:\\test.xls;"


' cnAdo.Open()


' cmCommand.Connection = cnAdo


' cmCommand.CommandText = "SELECT * FROM [Sheet1$]"


' cmCommand.CommandType = CommandType.Text


' Return cmCommand.ExecuteReader(CommandBehavior.CloseConnection)


' Catch ex As Exception


' If cnAdo.State = ConnectionState.Open Then


' cnAdo.Close()


' End If


' Throw ex


' End Try


'End Function


'Private Sub DoJob()


' Dim drExcel As OleDbDataReader = GetData()


' Try


' Dim dc As New Enware_eStoreDataContext()


' Dim count As Integer = 0


' While drExcel.Read()


' If drExcel("ProductID") IsNot DBNull.Value Then


' Dim p As eStore_Product = dc.eStore_Products.FirstOrDefault(Function(s As eStore_Product) s.ID = CInt(drExcel("ProductID")))


' If p IsNot Nothing Then


' p.Name = drExcel("Name").ToString()


' p.Description = drExcel("Description").ToString()


' p.Image = drExcel("Image").ToString()


' p.Keyword = drExcel("Keyword").ToString()


' p.GroupCode = drExcel("GroupCode").ToString()


' p.Brochure = drExcel("Brochure").ToString()


' dc.SubmitChanges()


' Else


' Exit While


' End If


' Else


' Exit While


' End If


' count = count + 1


' End While


' Console.WriteLine("finished! - " + count.ToString() + " rows processed!")


' Console.ReadLine()


' Catch ex As Exception


' Console.WriteLine(ex)


' Console.ReadLine()


' Finally


' If drExcel IsNot Nothing Then


' drExcel.Close()


' End If


' End Try


'End Sub


Private Function GetOdbcDataReader() As OdbcDataReader


Dim con As New OdbcConnection()


Dim cmd As New OdbcCommand()


Try


con.ConnectionString = "Driver={Microsoft Excel Driver (*.xls)};DBQ=E:\\test.xls;"


con.Open()


cmd.Connection = con


cmd.CommandText = "SELECT * FROM [Sheet1$]"


cmd.CommandType = CommandType.Text


Return cmd.ExecuteReader(CommandBehavior.CloseConnection)


Catch ex As Exception


If con.State = ConnectionState.Open Then


con.Close()


End If


Throw ex


End Try


End Function


Private Sub DoJob1()


Dim drExcel As OdbcDataReader = GetOdbcDataReader()


Try


Dim dc As New Enware_eStoreDataContext()


Dim count As Integer = 0


While drExcel.Read()


If drExcel("ProductID") IsNot DBNull.Value Then


Dim p As eStore_Product = dc.eStore_Products.FirstOrDefault(Function(s As eStore_Product) s.ID = CInt(drExcel("ProductID")))


If p IsNot Nothing Then


p.Name = drExcel("Name").ToString()


p.Description = drExcel("Description").ToString()


p.Image = drExcel("Image").ToString()


p.Keyword = drExcel("Keyword").ToString()


p.GroupCode = drExcel("GroupCode").ToString()


p.Brochure = drExcel("Brochure").ToString()


dc.SubmitChanges()


Else


Exit While


End If


Else


Exit While


End If


count = count + 1


End While


Console.WriteLine("finished! - " + count.ToString() + " rows processed!")


Console.ReadLine()


Catch ex As Exception


Console.WriteLine(ex)


Console.ReadLine()


Finally


If drExcel IsNot Nothing Then


drExcel.Close()


End If


End Try


End Sub


End Module

Reference:

Reading and Writing Excel using OLEDB

MOSS Video Format

  • SharePoint will play all files that windows media player can play. If you have all codecs correctly installed for Media player, then you can host any file in SharePoint and then add a code that will make windows media player play the file.
  • But since the user may not have the correct codecs installed for their media player, the best format is wmv since windows media player is made to play .wmv files.
  • By Default Moss will allow us to upload File size up to 50 MB. Upload File size can be adjusted to up to 2 GB.
  • The best file size will be less than 20MB.

Reference:

Does Sharepoint play any video file?