Learning WPF, CSharp(C#) with me | Part #2

Part #2

Subject: Why each trainer stick to console based development when my intention is to learn how to make “real” applications?

Hi guys,

Have you taken a training for development recently? If you are an established developer in any technology stack, the most frustrating thing could be the “basics”, you would groan and stir loads in the seat when a junior trainer goes through the concepts, basic commands set etc & would try to make the logic behind the approach

For example, if you want to learn C#, that you could use Web applications or desktop applications, you have a preset mind that wants to develop the applications those a user could interact with visibly. Not something that open a console and shows you few outputs and closes down.

I have asked the same question to many junior trainers during the courses and none was ever able to give me satisfactory answer. During my last attempt to refresh my C# skills I came to a conclusion towards this irritating question and it is simple like this

A console application when you want to print something on the screen, you just write a code snippet like this

static void Main(){

Console.WriteLine(“Hello World”);

}

And if you want to do the same with a Desktop application, the efforts are like this

You design a form (I will not use the real technical terms here, not at this stage)

You will add textboxes or labels to show “Hello World” (and you don’t really know how to make them at the first level)

Then you will develop the code part that should show the “Hello World” finally when the application starts

So for a trainer it becomes easy to deal with code part, which is the most important element of an application, rather than trying to teach a student the GUI development.

I will try to explain what I have assumed using real examples

Hellow World console application

[code language=”csharp” gutter=”false”]
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace HellowWorldConsole

{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hellow World");
}
}

}
[/code]

Running the application will open a console window and show you the following

image

Now let us develop the same Hello World application using WPF

My GUI part has the following XAML Code

[code language=”xml” gutter=”false”]
<Window x:Class="HelloWorldWPF.MainWindow"
xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation"">http://schemas.microsoft.com/winfx/2006/xaml/presentation"</a&gt;
xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml"">http://schemas.microsoft.com/winfx/2006/xaml"</a&gt;
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<TextBox x:Name="HWorld" Margin="95,150,117,124"/>
</Grid>

</Window>
[/code]
and the code behind is

[code language=”csharp” gutter=”false”]

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

namespace HelloWorldWPF

{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.HWorld.Text = "Hello World";
}
}

}
[/code]

and the output of both portion is seen as below

image

Now, it’s a common tendency of a seasoned programmer to perfect the GUI, because it creates the initial appeal. As you could see my textbox and the text appearing is not in sync, the height of the textbox is much bigger than the text that it looks somewhat mismatch…the time spent to perfect the GUI could become a real hurdle to progress with the training which must be limited certain hours per course!

Instead the trainers would approach the course, trying to teach the student the maximum coding part, then once the students are familiar with the technology, letting them explore the GUI development (Unless the course has the GUI development exclusively listed under the curriculum)

Once the above idea settled within me comfortably, I managed to sit patiently and learn the “basics” better than ever & was able to map what I learned to GUI much easily. Interested? However, my approach with this series will be developing GUI elements along with the basic coding. Do you have a different approach? do let me know through comments.

with the 1st part of this series I have posted a complete WPF solution to demonstrate what C# with WPF could do. That solution has many issues, like I am not handling folder/file access permissions or threading which is a must requirement when a program is going to run for unprecedented periods.

Be with me and we will be looking at much of them in coming parts.

regards,

rajesh

Learning WPF, CSharp(C#) with me | Part #1

Part #1

Subject: A Simple File Listing Utility using WPF & CSharp (C#)

Okay guys

Here I am once again! This time trying to learn WPF with C# to build my own small utilities to make my “Admin work” a lot easier. Further, I use my own blog as a reference guide most of them time! So, you are most welcome to use my “notes”

A WPF project always has two parts, XAML and the code behind. While XAML maintains the GUI part of it, Code part is where you write supporting code.

[code language=”xml” gutter=”false”]
<Window x:Class="WpflisttoGrid.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot; Title="MainWindow" Height="513" Width="877" Loaded="Window_Loaded">
<DockPanel>
<Menu DockPanel.Dock="Top" Height="24"></Menu>

<StatusBar DockPanel.Dock="Bottom" Height="24">
<StatusBarItem x:Name="StatusItem" Content="Ready" Width="Auto" HorizontalAlignment="Left" VerticalAlignment="top"></StatusBarItem>
</StatusBar>

<Grid>
<GroupBox x:Name="MyParameters">
<Grid x:Name="MyParameters_Grid">
<Label x:Name="lblPath" Content="Folder" HorizontalAlignment="Left" Margin="6,19,0,0" VerticalAlignment="Top"/>
<Label x:Name="lblFileType" Content="File Type" HorizontalAlignment="Left" Margin="6,47,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="txtPath" HorizontalAlignment="Left" Height="23" Margin="83,22,0,0" TextWrapping="NoWrap" VerticalAlignment="Top" Width="258"/>
<TextBox x:Name="txtType" HorizontalAlignment="Left" Height="23" Margin="83,49,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button x:Name="buttonFldrOpen" HorizontalAlignment="Left" Margin="346,22,0,0" VerticalAlignment="Top" Height="23" Click="buttonFldrOpen_Click" >
<StackPanel Orientation="Horizontal">
<Image Source="/Resources/folder_Open_32xMD.png" Stretch="Uniform" Height="18" Width="22"/>
</StackPanel>
</Button>
<Button Content="Process" HorizontalAlignment="Left" Margin="83,84,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
</GroupBox>

<DataGrid x:Name="Grid1" Margin="68,159,89,40" IsReadOnly="True" SelectionChanged="Grid1_SelectionChanged" MouseDoubleClick="Grid1_MouseDoubleClick" SelectionUnit="Cell"/>

</Grid>

</DockPanel>

</Window>
[/code]

and the CSharp code portion as below

[code language=”csharp” gutter=”false”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Data;
//Required for folder browswer & so
using System.Windows.Forms;

namespace WpflisttoGrid
{
///
<summary>
/// Interaction logic for MainWindow.xaml
/// </summary>

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//Setup the gridview to generate columns automatically against the file lists
this.Grid1.AutoGenerateColumns = true;
//We will store the text box values into local variables for easy understanding
//You may refer them straight away as defined columns
string filepath = this.txtPath.Text;
string filetype = this.txtType.Text;
//We will build a LIST of class myFiles
//Which will have chosen columns from the directory info file info results
List<myFiles> newList = new List<myFiles>();
try
{
foreach (FileInfo myfile in (new DirectoryInfo(@filepath).GetFiles(filetype, SearchOption.AllDirectories)))
//SearchOption.TopDirectoryOnly lists files from the top folder, ie, if a folder has sub-folders within
//SearchOption.TopDirectoryOnly will isolate the top folder & list all files from it
//SearchOption.AllDirectories will recursively pick all files from all folders those match type of files PDF
//As a developer who is learning
//I will leave enhancements to your logic
//This application could have
//Files those matching certain "contents"
//You can change the SearchOption.AllDirectories to SearchOption.TopDirectoryOnly programmatically…etc
{
//Calculate the time difference between the file creation and as on this moment
double _fileAge = Math.Round((DateTime.Now – myfile.CreationTime).TotalDays, 0);
//Add rows to the new list using new instance of the "Constructor" myFiles by passing the file details
newList.Add(new myFiles(myfile.FullName.ToString(), myfile.CreationTime, _fileAge));
}
//The following you could use for showing additional details
//this.StatusItem.Content = myfileList.Count().ToString();
//this.Grid1.ItemsSource = myfileList;
//System.Diagnostics.Debug.WriteLine(myfileList.Count());
this.Grid1.ItemsSource = newList;
this.Grid1.Columns[0].Header = "File Name";
this.Grid1.Columns[1].Header = "Creation Time";
this.Grid1.Columns[2].Header = "File Age(Days)";
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message + ex.Source);
}
}

private void Grid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

}
private void Grid1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
// System.Windows.MessageBox.Show()
//https://stackoverflow.com/questions/47309073/c-sharp-wpf-gridview-will-not-show-data-unless-clicked
try
{
var cellInfo = Grid1.SelectedCells[0];
var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text;
//System.Windows.MessageBox.Show(content);
System.Diagnostics.Process.Start(@content);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message + ex.Source);
}
}

private void buttonFldrOpen_Click(object sender, RoutedEventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = false; //Don’t allow users to create new folders from this dialogue
folderDlg.RootFolder = Environment.SpecialFolder.MyComputer;
// Show the FolderBrowserDialog.
DialogResult result = folderDlg.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
this.txtPath.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
}
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.txtType.Text = "*.*";
}
}

public class myFiles
{
public string fName { get; set; }
public DateTime fCreationDate { get; set; }
public double fAge { get; set; }

public myFiles(string fname, DateTime fcdate, double fage)
{
fName = fname;
fCreationDate = fcdate;
fAge = fage;

}

}
}
[/code]

This project should be used as a pilot to learn both WPF & CSharp (C#) rather than a commercial product as I am not using threading or channeling the background works. So once the Process button clicked, the GUI become irresponsive until the file lists populated, and could make a user feel the system is stuck.

Once the file list is populated in the GridView, one can double click the file name to start a fresh instance of associated program. So be careful, you may be running an executable that could cause unexpected problems.

Optionally you may download the Visual Studio Solution from here

regards,

rajesh

C# (CSharp, C-Sharp) Windows Active Directory last logon

Hi guys

Please note, many threads were referred in order to compile the script attached below & all I did was re-arranging in order for better reading/formatting

(And I insure that the script works under following scenarios:

  1. You are a domain administrator
  2. You are administrating Windows 2003 onwards Windows domain
  3. Your puter is connected to the domain network ;)

)

Referenced websites/threads

  1. http://stackoverflow.com/questions/15775264/searching-for-lastlogon-attribute-of-user-in-multiple-domain-servers
  2. https://www.codeproject.com/kb/security/lastlogonacrossallwindows.aspx#_comments
  3. http://codebeautify.org/csharpviewer (for formatting the C# code)

How to test the code

Start Visual Studio (I am using 2013 Professional edition, you can use any of the community editions to test the scripts)

Create a new C# Console Application and name it llogon (else you need to change the namespace name “llogon” according to the name you have chosen for your new project.

Add the following references to your project

  1. “Framework -> System.DirectoryServices”
  2. “Browse and add -> C:\Windows\System32\activeds.tlb”

 

[code language=”csharp” gutter=”false”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//Added by Rajesh

//using System.Management;
//using System.Data;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
//http://stackoverflow.com/questions/33274162/the-namespace-of-iadslargeinteger
//ActiveDS namespace
using ActiveDs; // Namespace added via ref to C:\Windows\System32\activeds.tlb
//https://www.codeproject.com/kb/security/lastlogonacrossallwindows.aspx

namespace llogon
{
class Program
{
static void Main(string[] args)
{
// Get the root entry
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
string configurationNamingContext =
(string)rootDSE.Properties["configurationNamingContext"].Value;
string defaultNamingContext =
(string)rootDSE.Properties["defaultNamingContext"].Value;
Dictionary<string, Int64> lastLogons = new Dictionary<string, Int64>();
// Get all the domain controllers
DirectoryEntry deConfig = new DirectoryEntry("LDAP://" + configurationNamingContext);
DirectorySearcher dsConfig = new DirectorySearcher(deConfig);
dsConfig.Filter = "(objectClass=nTDSDSA)";
foreach (SearchResult srDomains in dsConfig.FindAll())
{
DirectoryEntry deDomain = srDomains.GetDirectoryEntry();
if (deDomain != null)
{
string dnsHostName =
deDomain.Parent.Properties["DNSHostName"].Value.ToString();
// Get all the users for that domain
DirectoryEntry deUsers =
new DirectoryEntry("LDAP://" + dnsHostName + "/" + defaultNamingContext);
DirectorySearcher dsUsers = new DirectorySearcher(deUsers);
dsUsers.Filter = "(&(objectCategory=person)(objectClass=user))";
foreach (SearchResult srUsers in dsUsers.FindAll())
{
DirectoryEntry deUser = srUsers.GetDirectoryEntry();
if (deUser != null)
{
// Get the distinguishedName and lastLogon for each user
// Save the most recent logon for each user in a Dictionary object
string distinguishedName = deUser.Properties["distinguishedName"].Value.ToString();
Int64 lastLogonThisServer = new Int64();
if (deUser.Properties["lastLogon"].Value != null)
{
IADsLargeInteger lgInt =
(IADsLargeInteger)deUser.Properties["lastLogon"].Value;
lastLogonThisServer = ((long)lgInt.HighPart << 32) + lgInt.LowPart;
}

// Save the most recent logon for each user in a Dictionary object
if (lastLogons.ContainsKey(distinguishedName))
{
if (lastLogons[distinguishedName] < lastLogonThisServer)
{
lastLogons[distinguishedName] = lastLogonThisServer;
}
}
else
{
lastLogons.Add(distinguishedName, lastLogonThisServer);
}
string readableLastLogon = DateTime.FromFileTime(lastLogonThisServer).ToString();
Console.WriteLine("User: " + distinguishedName + "Last logon: " +readableLastLogon);
}
}
Console.ReadLine();
}
}

}
}
}

[/code]

Try the code & if you are stuck somewhere, do let me through the comments. I am working on a WPF C# project for a simple Active Directory Reporter / Asset Management System using WMI. Stay tuned & I will soon post the entire solution here :)

regards,

rajesh

 

It’s been long time!

Hello guys!

I know, there were NOT much to post throughout last few months about Oracle as I am nose down into one of the development platforms that I hardly desired for developing business applications.

For me, it was always Oracle forms and reports. The easiest, the most robust development tools for BUSINESS applications which is supported by the ease of SQL, PL/SQL

I am doing loads of research with C# & SQL database, which will be the main technologies behind our next proposed ERP suite. After spending almost 15 years with Forms and reports, I don’t see Oracle is too keen about modernizing their most loved development tools & the latest release lacks loads of features those would have helped to reclaim the desktop based business applications.

Wondering whether there is still room for desktop applications, especially for businesses? dude! there is, and there will be!

 

So stay tuned, I will start posting my “findings” about C#, who knows may be some sample applications using Windows forms or WPF & Oracle database in near future!

regards,

rajesh

 

VB.net | Active Directory | Get last logon for computer/user account

Ever wondered how to fetch the last logon details for a domain member computer or user? Using .Net Microsoft has made it pretty easier for the developers to populate the active directory attributes to desired data repositories, however getting the last logon date time value still remains a complex stuff (for beginners like us), especially when your domain consist of multiple domain controllers and they are spread across different geographical areas and subnets :)

After dwelling for long a while, I came across a C# code snippet @ http://www.codeproject.com/Articles/19181/Find-LastLogon-Across-All-Windows-Domain-Controlle that was mostly built against http://www.rlmueller.net/Last%20Logon.htm

I had to copy the codes those were split into multiple blocks for proper explanations, re-arrange and then using the online C# to VB.Net converters, convert to readable VB.Net coding. Again, there were few mismatches and I was able to figure them out through stackoverflow & tech forums posts.

Without going on with what and how I did it, here comes the complete coding. Please note, this is a console application solution, and you should add the references as seen with the below image in order to successfully call the methods and types

Ref

[code language=”vb” gutter=”false” wraplines=”true”]
Imports System.DirectoryServices
Imports ActiveDs

Module Module1

”’ &lt;summary&gt;
”’ You should able to easily convert this console application to windows form application
”’ with least efforts
”’ Original code was posted with http://www.codeproject.com/Articles/19181/Find-LastLogon-Across-All-Windows-Domain-Controlle
”’ using C#, I converted most of the C# Codes using online converter(s)
”’ and ammended at few places, as the code block provided with the project were not fetching decent results
”’ Rajesh Thampi / 15-Jan-2015 | w7bugs at gmail dot com | windows7bugs.wordpress.com
”’ &lt;/summary&gt;
”’ &lt;remarks&gt;&lt;/remarks&gt;
Sub Main()
‘Get the root of the directory data tree on a directory server.
Dim rootDse As New DirectoryEntry(&quot;LDAP://rootDSE&quot;)
‘Dictionary object to hold the records retrived by the search
Dim lastLogons As Dictionary(Of String, Int64) = New Dictionary(Of String, Int64)
‘Local variable for holding formatted last logon values in datetime format
Dim llogon As DateTime = Nothing

‘for User last logon
‘Dim TargetUsername As String = &quot;george&quot; ‘ -&gt; Pass sAMAccountName
‘Dim objType As Integer = 805306368 ‘-&gt; 805306368 User | 805306369 Computer

‘for Computer
Dim TargetUsername As String = &quot;JOSE-KSP$&quot; ‘ -&gt; Pass sAMAccountName
Dim objType As Integer = 805306369 ‘-&gt; 805306368 User | 805306369 Computer

‘Loop through all available domain controllers
For Each dsDC As DirectoryServices.ActiveDirectory.DomainController In _
DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain.DomainControllers
‘Print the individual domain controller name
‘Debug.Write(dsDC.Name &amp; vbCrLf) ‘ Uncomment for print
‘Get the Entry details for domain controller
Dim dirEntry As DirectoryEntry = New DirectoryEntry(&quot;LDAP://&quot; + dsDC.Name + &quot;/&quot; + DirectCast(rootDse.Properties(&quot;defaultNamingContext&quot;).Value, String))
‘Define searcher for the objects of interest
Dim dirObjects As DirectorySearcher = New DirectorySearcher(dirEntry)
‘Define a large integer to hold the COM object translated value
‘ActiveDS COM object is a MUST reference, yet to find another way to deal with highpart, lowpart values obtained from &quot;lastlogon&quot;
Dim lastLogonThisServer As Int64 = New Int64()
‘Set up the filter for object to be returned through findall method
dirObjects.Filter = &quot;(&amp;(sAMAccountType=&quot; &amp; objType &amp; &quot;)(sAMAccountName=&quot; &amp; TargetUsername &amp; &quot;))&quot;
‘ Loop through the records found
For Each objRecords In dirObjects.FindAll()
‘Get the directory entry, this will return all the attributes associated with the object (Computer/User)
Dim dirObj As DirectoryEntry = objRecords.GetDirectoryEntry()
If Not dirObj Is Nothing Then
‘ Get the distinguishedName and lastLogon for each user

Dim distinguishedName As String = dirObj.Properties(&quot;distinguishedName&quot;).Value.ToString()

Try

If Not dirObj.Properties(&quot;lastLogon&quot;).Value Is Nothing Then
Dim lgIntas As ActiveDs.LargeInteger = dirObj.Properties(&quot;lastLogon&quot;).Value
Dim lngHigh As Long = lgIntas.HighPart
Dim lngLow As Long = lgIntas.LowPart
lastLogonThisServer = (lngHigh * (2 ^ 32) – lngLow)

End If

Catch ex As Exception
Debug.Write(ex.Message)
End Try
‘Different date time formats you can play around with
‘Dim format As String = &quot;MMM ddd d HH:mm yyyy&quot; -&gt; Jan Thu 15 08:11 2015
‘Dim format As String = &quot;dd/MMM/yyyy HH:mm tt&quot; -&gt; 15/Jan/2015 08:36 AM
‘Debug.Write(distinguishedName &amp; &quot;;&quot; _
‘&amp; DateTime.FromFileTime(lastLogonThisServer).ToString(format, Globalization.CultureInfo.InvariantCulture) &amp; vbCrLf)

‘Save the most recent logon for each user in a Dictionary object
‘How it works
‘lastLogons dictionary object has two parts, key and corresponding value
‘Prior adding a new record, using ContainsKey call we can check the array for existing keys
‘With this example, the key is &quot;distinguishedName&quot;
‘If the distinguishedName as key found

If lastLogons.ContainsKey(distinguishedName) Then
‘We compare the latest fetched logon date integer value against the key value of the dictionary object
If lastLogons(distinguishedName) &lt; lastLogonThisServer Then
‘If the existing value is smaller than the new value &quot;lastLogonThisServer&quot; holds
lastLogons(distinguishedName) = lastLogonThisServer
‘We will update the existing key value with recent lastLogonThisServer value
End If
Else
‘We will add a new entry to the dictionary object
lastLogons.Add(distinguishedName, lastLogonThisServer)
End If
End If
Next
Next
‘Now we will loop through the dictionary object and fetch the details
‘For a single user/computer the dictionary object will not have more than one entry
For Each kvp As KeyValuePair(Of String, Int64) In lastLogons
Dim v1 As String = kvp.Key
Dim v2 As DateTime = DateTime.FromFileTime(kvp.Value).ToString()
‘ llogon = v2
Dim format As String = &quot;dd/MMM/yyyy HH:mm tt&quot;
Debug.Write(&quot;Distinguished Name :&quot; &amp; v1 &amp; &quot;; Last logged :&quot; &amp; v2.ToString(format) &amp; vbCrLf)

Next

End Sub

End Module
[/code]

You may download the solution from https://drive.google.com/file/d/0B-3iVeOMTCbWWFliTGN1NmNxMjQ/view?usp=sharing

regards,

rajesh

A simple asp.net application for listing files and folders within a folder

We tease each other calling “Google Programmers” occasionally as we just cut and paste code from forums/websites and meet new business requirements and deadlines.

We started revamping our intranet site recently and was frantically looking at a prospective of converting few .asp driven details using .net application(s)

Our primary requirement was to list the content of a folder, along with subdirectories and files (mostly .pdf and .doc/.docx/.xls/.xlsx)

After loads of googling we came across two potential solutions and they were

http://www.4guysfromrolla.com/articles/090110-1.aspx

http://www.encodedna.com/2013/08/extract-display-files-from-folder-and-bind-with-gridview.htm

The first solution was “too” professional approach for guys like us, who hardly have anything more than few hours of experiences with .net programming

The second solution looked more appropriate as we were looking at something which could be easily altered and adopted to our particular requirement.

Hence we copied the scripts available with the link and started altering them, and with our “extreme” level of exposure to the technology, almost after 72 hours we were able to shape up something which fits into our requirements, somehow and we are sharing the same with you.

We know, it could be done much easier or in a simpler manner, well that part we are leaving for the seasoned .net developers.

First create a .aspx file with name “Default” (eg:Default.aspx) and copy the following code inside the file (Notepad++)

[sourcecode language=”html” padlinenumbers=”true”]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>Display | Bind Files from Folder to GridView</title>
<style type="text/css">
div { font:11px Verdana; width:750px }
.grid { width:100%; font:inherit; background-color:#FFF; border:solid 1px #525252}
.grid td { font:inherit; padding:2px; border:solid 1px #C1C1C1; color:#333; text-align:left;
text-transform: capitalize}
.grid th { padding:3px; color:#FFF; background:#424242 url(grd.png) repeat-x top;
border-left:solid 1px #525252; font:inherit; text-align:center; text-transform:uppercase}
#drop1 { width:70px; padding:3px }
</style>
</head>
<body>
<%– <%
Response.Write("<br/> " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/> " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/> " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/> " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/> " + HttpContext.Current.Request.Url.PathAndQuery);
%>–%>
<form id="form1" runat="server">
<div>
<%–LISTBOX SHOWING A LIST OF FILE TYPES.–%>
<%– <p> <asp:ListBox id="drop1" rows="3" runat="server">
<asp:ListItem selected="true">All</asp:ListItem>
<asp:ListItem>pdf</asp:ListItem>
<asp:ListItem>jpg</asp:ListItem>
<asp:ListItem>png</asp:ListItem>
<asp:ListItem>txt</asp:ListItem>
<asp:ListItem>doclt</asp:ListItem>
</asp:ListBox>
<input type="button" id="btShowFiles" onserverclick="btShowFiles_Click" value="Show Files" runat="server" />
</p>–%>

<%–ADD A GRIDVIEW WITH FEW COLUMNS–%>
<asp:GridView ID="GridView2" CssClass="grid" GridLines="None" ShowFooter="true"
AllowPaging="true" PageSize="5" AutoGenerateColumns="false"
runat="server">

<Columns>

<asp:TemplateField HeaderText="Folder(s)">
<ItemTemplate>
<asp:HyperLink runat="server" ID="HyperLink1" Text='<%# Eval("Name") %>’ NavigateUrl='<%# HttpContext.Current.Request.Url.AbsoluteUri +"/"+ Eval("Name") %>’ />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

<asp:GridView ID="GridView1" CssClass="grid" GridLines="None" ShowFooter="true"
AllowPaging="true" PageSize="20" AutoGenerateColumns="false"
OnPageIndexChanging="GridView1_PageIndexChanging" runat="server">

<Columns>

<asp:TemplateField HeaderText="Name">

<ItemTemplate>
<%–<asp:Label ID="lblName" runat="server" Text='<%#System.IO.Path.GetFileNameWithoutExtension(Eval("Name").ToString()) %>’></asp:Label>–%>
<asp:HyperLink runat="server" ID="HyperLink2" Text='<%# System.IO.Path.GetFileNameWithoutExtension(Eval("Name").ToString()) %>’ NavigateUrl='<%#
Request.QueryString["p"] +"/"+ Eval("Name") %>’ />
</ItemTemplate>
</asp:TemplateField>

<%–
<asp:TemplateField HeaderText="File Length">
<ItemTemplate><asp:Label ID="lblLen" runat="server" Text='<%#Eval("Length")%>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Extention">
<ItemTemplate><asp:Label ID="lblFileType" runat="server" Text='<%#Eval("Extension")%>’>
</asp:Label></ItemTemplate>
</asp:TemplateField>–%>
<asp:TemplateField HeaderText="Creation Date & Time">
<ItemTemplate><asp:Label ID="lblDateTime" runat="server" Text='<%#Eval("CreationTime")%>’>
</asp:Label></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

<%–A LABEL SHOWING NUMBER OF FILES FOUND IN THE FOLDER.–%>
<p><asp:Label Text="" ID="lblMsg" runat="server"></asp:Label></p>
</div>
</form>
</body>
</html>
[/sourcecode]

Now create another file “Default.aspx.cs” and copy the below code inside the file

[sourcecode language=”csharp”]
using System;
using System.IO;
using System.Globalization;

public partial class _Default : System.Web.UI.Page
{

protected void btShowFiles_Click(object sender, EventArgs e)
{
// ViewState["FileType"] = drop1.SelectedValue; // GET THE FILE TYPE.
GetFilesFromFolder();
}

// GRIDVIEW PAGING.
protected void GridView1_PageIndexChanging(object sender,
System.Web.UI.WebControls.GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GetFilesFromFolder();
}

protected void GetFilesFromFolder()
{
String pathname = Request.QueryString["p"];

//String pathname;

// pathname = Request.QueryString["p"];

//response.redirect("a.aspx?ids=1&val=100",true)

//and in the second page that is a.aspx

//a=Request.QueryString("ids")

//b= Request.QueryString("val")

// GET A LIST OF FILES FROM A SPECIFILED FOLDER.

DirectoryInfo objDir = new DirectoryInfo(Server.MapPath(pathname));

//(@"D:\Dell Drivers");
//(Server.MapPath("listfiles\\"));

FileInfo[] listfiles = objDir.GetFiles("*");

DirectoryInfo[] listDirs = objDir.GetDirectories(".");

if (listDirs.Length > 0)
{
GridView2.Visible = true;
GridView2.DataSource = listDirs;
GridView2.DataBind();
}
else
{
GridView2.Visible = false;
}

if (listfiles.Length > 0)
{
// BIND THE LIST OF FILES (IF ANY) WITH GRIDVIEW.
GridView1.Visible = true;
GridView1.DataSource = listfiles;
GridView1.DataBind();

lblMsg.Text = listfiles.Length + " files found";
}
else {
GridView1.Visible = false ;
lblMsg.Text = "No files found";
}
}
protected void Page_Load(object sender, EventArgs e)
{
GetFilesFromFolder();
}
}
[/sourcecode]

Now move both the files to your web application folder. We were using the default “C:\inetpub\wwwroot” for the testing, hence moved the files to there.

Now you can start calling the application like following

http://localhost/Default.aspx?p=memos

Where memos is an actually folder available within “C:\inetpub\wwwroot” path

If you have folders within the “memos” folder, the application will present you view like following

image

Based on whether you have subfolders within the “memos” folder the application will either display or hide the Folder(s) grid, the same applies to Files grid as well

The best part is, this application can drill down into any level of nested folders and populate folder and file lists as URLs.

We thank A2S from forums.asp.net for helping us to strip out the extensions from filenames. Please refer to the below link for more details.

http://forums.asp.net/t/1958264.aspx?Stripping+the+extension+from+file+name+derived+using+Eval+Name+

Enjoy guys!

After all it is another wonderful Christmas time

regards,

for Windows7bugs

rajesh