Const IncludeDirectory = "F:\Development\VBS Includes\"

includeFile "adovbs"
includeFile "CLogger"
includeFile "Public_Functions"
includeFile "VBSEnvironment"
includeFile "Database_Class"
includeFile "lib.collections"

Dim props,fieldNamesArray
Dim oConn,fso,includedFile,rs
Dim fixedTableName,tableName
Dim PrimaryKeyDictionary
Set oConn = WScript.CreateObject("ADODB.Connection")
Set fso = WScript.CreateObject("Scripting.Filesystemobject")
oConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Development\Tracking_Kits\Data\webdata - Copy.mdb"
'oConn.ConnectionString = "Provider=SQLOLEDB;Data Source=danielsubuntu,15789;Initial Catalog=northwind;User Id=sa;Password=SunBrightShine!;"

Init
		fixedTableName = Replace(rs("TABLE_NAME")," ","_")
		tableName =  rs("TABLE_NAME")
    Do While Not rs.EOF
    		fixedTableName = Replace(rs("TABLE_NAME")," ","_")
		tableName =  rs("TABLE_NAME")
		 'If tableName <> "meta_migrations" Then
    	If tableName <> "meta_migrations" AND tableName = "InkjetRecords" Then

        debug.WriteLine(tableName)
        If Not fso.FolderExists(ScriptDirectory()& "Controllers\"& fixedTableName) Then fso.CreateFolder(ScriptDirectory()& "Controllers\"& fixedTableName)
        If Not fso.FolderExists(ScriptDirectory()& "Controllers\") Then fso.CreateFolder(ScriptDirectory()& "Controllers\")
        If Not fso.FolderExists(ScriptDirectory()& "Views\" & Replace(tableName," ","_")) Then fso.CreateFolder(ScriptDirectory()& "Views\" & Replace(tableName," ","_"))
        Set file = fso.CreateTextFile(ScriptDirectory()& "DomainModels\" & fixedTableName & "Repository.asp",True)
        includedFile.WriteLine("<!--#include file=""DomainModels/"& fixedTableName & "Repository.asp""-->")
        file.WriteLine("<%")
        file.WriteLine("'=======================================================================================================================")
        file.WriteLine("' " & fixedTableName & " Model")
        file.WriteLine("'=======================================================================================================================")
        file.WriteLine("")
        file.WriteLine("Class " & fixedTableName & "Model_Class")
        file.WriteLine("	Public Validator")
        file.WriteLine("	Public Class_Get_Properties")
        file.WriteLine("")
        InitFieldNameIterator ' This Sub is werid and needs to be looked at 
		fieldNamesArray = props.toArray()
        file.WriteLine("")
        file.WriteLine("	Private Sub Class_Initialize")
        file.WriteLine("		'ValidateExitsts Me, """",""""")
        file.WriteLine("		Class_Get_Properties = Array(""" & Join (fieldNamesArray,", ") & """)")
        file.WriteLine("	End Sub")
        file.WriteLine("")
        file.WriteLine("End CLass")
        file.WriteLine("")
        file.WriteLine("'=======================================================================================================================")
        file.WriteLine("' " & tableName & " Repository")
        file.WriteLine("'=======================================================================================================================")
        file.WriteLine("")
        file.WriteLine("Class " & fixedTableName & "Repository_Class") 
        file.WriteLine("")
        file.WriteLine("	Public Function FindBy" & PrimaryKeyDictionary(tableName) & "("& PrimaryKeyDictionary(tableName) & ")")
        file.WriteLine("		dim sql : sql = ""Select ["  & Join (fieldNamesArray,"], [") & "] FROM [" & tableName & "] WHERE " & PrimaryKeyDictionary(tableName) & " = ?""")
        file.WriteLine("		dim rs : set rs = DAL.Query(sql," & PrimaryKeyDictionary(tableName) & ")")
        File.WriteLine("    	If rs.EOF then")
        File.WriteLine("    		Err.Raise 1, """ & fixedTableName & "Repository_Class"", "& fixedTableName &"NotFoundException(""" & PrimaryKeyDictionary(tableName) &""", "& PrimaryKeyDictionary(tableName) & ")")
        File.WriteLine("		Else")
		File.WriteLine("			set FindBy" & PrimaryKeyDictionary(tableName) & " = Automapper.AutoMap(rs,""" & tableName & "Model_Class" & """)")
        file.WriteLine("        End If")
        file.WriteLine("	End Function")
        file.WriteLine("")
        file.WriteLine("  	Public Function GetAll(orderBy)")
        file.WriteLine("		set GetAll = Find(empty,orderBy)")
        file.WriteLine("   	End Function")
        file.WriteLine("")	
        file.WriteLine("    Public Function Find(where_kvarray, order_string_or_array)")
        file.WriteLine("		dim sql : sql = ""Select ["  & Join (fieldNamesArray,"], [") & "] FROM [" & tableName  & "]""")
        File.WriteLine("")
        File.WriteLine(" 		If Not IsEmpty(where_kvarray) then")
        File.WriteLine("			sql = sql & "" WHERE """)
        File.WriteLine("				dim where_keys, where_values")
        File.WriteLine("				KVUnzip where_kvarray, where_keys, where_values")
        file.WriteLine("")
        file.WriteLine("			dim i")
        file.WriteLine("			For i = 0 to UBound(where_keys)")
        file.WriteLine("				If i > 0 then sql = sql & "" AND """)
        file.WriteLine("				sql = sql & "" "" & where_keys(i) & "" """)
        file.WriteLine("			Next")
        file.WriteLine("		End If")
        file.WriteLine("")
        file.WriteLine("		If Not IsEmpty(order_string_or_array) then")
        file.WriteLine("			sql = sql & ""ORDER BY """)
        file.WriteLine("			If IsArray(order_string_or_array) then")
        file.WriteLine("				dim order_array : order_array = order_string_or_array")
        file.WriteLine("				For i = 0 to UBound(order_array)")
        file.WriteLine("					If i > 0 then sql = sql & "", """)
        file.WriteLine("					sql = sql & "" "" & order_array(i)")
        file.WriteLine("				Next")
        file.WriteLine("			Else")
        file.WriteLine("				sql = sql & order_string_or_array & "" """)
        file.WriteLine("			End If")
        file.WriteLine("		End If")
        file.WriteLine("")
        file.WriteLine("		dim rs : set rs = DAL.Query(sql, where_values)")
        file.WriteLine("		set Find = " & fixedTableName & "List(rs)")
        file.WriteLine("		Destroy rs")
        file.WriteLine("	End Function")
        file.WriteLine("")
        file.WriteLine("	Public Function FindPaged(where_kvarray, order_string_or_array, per_page, page_num, ByRef page_count, ByRef record_count)")
        file.WriteLine("		dim sql : sql = ""Select ["  & Join (fieldNamesArray,"], [") & "] FROM [" & tableName & "]""")
        File.WriteLine("")
        File.WriteLine(" 		If Not IsEmpty(where_kvarray) then")
        File.WriteLine("			sql = sql & "" WHERE """)
        File.WriteLine("				dim where_keys, where_values")
        File.WriteLine("				KVUnzip where_kvarray, where_keys, where_values")
        file.WriteLine("")
        file.WriteLine("			dim i")
        file.WriteLine("			For i = 0 to UBound(where_keys)")
        file.WriteLine("				If i > 0 then sql = sql & "" AND """)
        file.WriteLine("				sql = sql & "" "" & where_keys(i) & "" """)
        file.WriteLine("			Next")
        file.WriteLine("		End If")
        file.WriteLine("")
        file.WriteLine("		If Not IsEmpty(order_string_or_array) then")
        file.WriteLine("			sql = sql & ""ORDER BY """)
        file.WriteLine("			If IsArray(order_string_or_array) then")
        file.WriteLine("				dim order_array : order_array = order_string_or_array")
        file.WriteLine("				For i = 0 to UBound(order_array)")
        file.WriteLine("					If i > 0 then sql = sql & "", """)
        file.WriteLine("					sql = sql & "" "" & order_array(i)")
        file.WriteLine("				Next")
        file.WriteLine("			Else")
        file.WriteLine("				sql = sql & order_string_or_array & "" """)
        file.WriteLine("			End If")
        file.WriteLine("		End If")
        file.WriteLine("")
        file.WriteLine("		dim list : set list = new LinkedList_Class")
        file.WriteLine("		dim rs   : set rs   = DAL.PagedQuery(sql, where_values, per_page, page_num)")
        file.WriteLine("")
        file.WriteLine("		If Not rs.EOF and Not (IsEmpty(per_page) and IsEmpty(page_num) and IsEmpty(page_count) and IsEmpty(record_count)) then")
        file.WriteLine("			rs.PageSize     = per_page")
        file.WriteLine("			rs.AbsolutePage = page_num")
        file.WriteLine("			page_count      = rs.PageCount")
        file.WriteLine("			record_count    = rs.RecordCount")
        file.WriteLine("		End If")
        file.WriteLine("")
        file.WriteLine("		set FindPaged = Paged"& fixedTableName & "List(rs, per_page)")
        file.WriteLine("		Destroy rs")    
        file.WriteLine("	End Function")
        file.WriteLine("")
        file.WriteLine("	Public Function SearchTablePaged(where_kvarray, order_string_or_array, per_page, page_num, ByRef page_count, ByRef record_count)")
        file.WriteLine("		dim sql : sql = ""Select ["  & Join (fieldNamesArray,"], [") & "] FROM [" & tableName & "]""")
        File.WriteLine("")
        File.WriteLine(" 		If Not IsEmpty(where_kvarray) then")
        File.WriteLine("			sql = sql & "" WHERE """)
        File.WriteLine("				dim where_keys, where_values")
        File.WriteLine("				KVUnzip where_kvarray, where_keys, where_values")
        file.WriteLine("")
        file.WriteLine("			dim i")
        file.WriteLine("			For i = 0 to UBound(where_keys)")
        file.WriteLine("				If i > 0 then sql = sql & "" OR""")
        file.WriteLine("				sql = sql & "" "" & where_keys(i) & "" LIKE ?""")
        file.WriteLine("			Next")
        file.WriteLine("		End If")
        file.WriteLine("")
        file.WriteLine("		If Not IsEmpty(order_string_or_array) then")
        file.WriteLine("			sql = sql & "" ORDER BY """)
        file.WriteLine("			If IsArray(order_string_or_array) then")
        file.WriteLine("				dim order_array : order_array = order_string_or_array")
        file.WriteLine("				For i = 0 to UBound(order_array)")
        file.WriteLine("					If i > 0 then sql = sql & "", """)
        file.WriteLine("					sql = sql & "" "" & order_array(i)")
        file.WriteLine("				Next")
        file.WriteLine("			Else")
        file.WriteLine("				sql = sql & order_string_or_array & "" """)
        file.WriteLine("			End If")
        file.WriteLine("		End If")
        file.WriteLine("")
        file.WriteLine("		dim list : set list = new LinkedList_Class")
        file.WriteLine("		dim rs   : set rs   = DAL.PagedQuery(sql, where_values, per_page, page_num)")
        file.WriteLine("")
        file.WriteLine("		If Not rs.EOF and Not (IsEmpty(per_page) and IsEmpty(page_num) and IsEmpty(page_count) and IsEmpty(record_count)) then")
        file.WriteLine("			rs.PageSize     = per_page")
        file.WriteLine("			rs.AbsolutePage = page_num")
        file.WriteLine("			page_count      = rs.PageCount")
        file.WriteLine("			record_count    = rs.RecordCount")
        file.WriteLine("		End If")
        file.WriteLine("")
        file.WriteLine("		set SearchTablePaged = Paged"& fixedTableName & "List(rs, per_page)")
        file.WriteLine("		Destroy rs")    
        file.WriteLine("	End Function")
        file.WriteLine("")
        file.WriteLine("	Private Function Paged"& fixedTableName & "List(rs, per_page)")
        file.WriteLine("    	dim list : set list = new LinkedList_Class")
        file.WriteLine("")
        file.WriteLine("		dim x : x =0")
        file.WriteLine("		Do While x < per_page and Not rs.EOF")
        file.WriteLine("			list.Push Automapper.AutoMap(rs, new " & fixedTableName & "Model_Class" & ")")
        file.WriteLine("			x = x +1")
        file.WriteLine("			rs.MoveNext")
        file.WriteLine("		Loop")
        file.WriteLine("		set Paged"& fixedTableName & "List = list")
        file.WriteLine("	End Function")
        file.WriteLine("")
        file.WriteLine("	Private Function " & fixedTableName &"NotFoundException(ByVal field_name, ByVal field_val)")
        file.WriteLine("			 "& fixedTableName & "NotFoundException = """ & fixedTableName & " was not found with "" & field_name & "" of '"" & field_val & ""'.""")
        file.WriteLine("	End Function")
       	file.WriteLine("")
       	file.WriteLine("	Private Function " & fixedTableName & "List(rs)")
       	file.WriteLine("		dim list : set list = new LinkedList_Class")
       	file.WriteLine("		dim model")
       	file.WriteLine("")
       	file.WriteLine("		Do until rs.EOF")
       	file.WriteLine("			set model = new " & fixedTableName & "Model_Class")
       	file.WriteLine("			list.Push Automapper.AutoMap(rs, model)")
       	file.WriteLine("			rs.MoveNext")
       	file.WriteLine("		Loop")
       	file.WriteLine("		set " & fixedTableName & "List = list")
       	file.WriteLine("	End Function")
       	file.WriteLine("")
       	file.WriteLine("	Public Sub AddNew(ByRef model)")
       	file.WriteLine("		dim sql : sql = ""INSERT INTO ["& fixedTableName & "] ("" &_")
       					For Fields = 1 To UBound(fieldNamesArray)-1
       						file.WriteLine("													""[" & fieldNamesArray(Fields) & "],"" &_")
       					Next
							file.WriteLine("													""[" & fieldNamesArray(UBound(fieldNamesArray)) & "])"" &_")
		file.Write("						""VALUES (?")
		For Fields = 1 To UBound(fieldNamesArray)-1
		file.Write(",?")
		Next
		file.Write(")""" & VbCrLf)
       	file.WriteLine("		DAL.Execute sql, Array(model." & fieldNamesArray(1) & ", _")
       						For Fields = 2 To UBound(fieldNamesArray) -1 
       							file.WriteLine("							  model." & fieldNamesArray(Fields) & ", _")
       						Next
       						file.WriteLine("							  model." & fieldNamesArray(UBound(fieldNamesArray)) & ")")
       						
       						
       	file.WriteLine("			sql = ""SELECT TOP 1 " & PrimaryKeyDictionary(tableName) & " FROM [" & fixedTableName & "] ORDER BY "& PrimaryKeyDictionary(tableName) & " DESC""")					
       	file.WriteLine("			dim rs : set rs = DAL.Query(sql, empty)")
       	file.WriteLine("			model." & PrimaryKeyDictionary(tableName) & " = rs(""" & PrimaryKeyDictionary(tableName) & """)")
       	file.WriteLine("			Destroy rs")
       	
       	file.WriteLine("	End Sub")
		file.WriteLine("")
       	file.WriteLine("	Public Sub Update(model)")       						
       	file.WriteLine("		dim sql : sql = ""UPDATE ["& fixedTableName & "] SET [" & fieldNamesArray(1) & "] = ?,"" &_")
       						
       						For Fields = 2 To UBound(fieldNamesArray) - 1
       							file.WriteLine("						""[" & fieldNamesArray(Fields) & "] = ?,"" &_")
       						Next
       						file.Write ("						""[" & fieldNamesArray(UBound(fieldNamesArray)) & "] = ?"" &_" & VbCrLf)
       	file.WriteLine("						"" WHERE ["& PrimaryKeyDictionary(tableName) & "] = ?""")
       	file.WriteLine("")
       	file.WriteLine("		DAL.Execute sql, Array(model." & fieldNamesArray(1) & ", _")
       						For Fields = 2 To UBound(fieldNamesArray) 
       							file.WriteLine("							  model." & fieldNamesArray(Fields) & ", _")
       						Next
       						        file.Write("							  model." & PrimaryKeyDictionary(tableName) & ")" & VbCrLf)       						        
       	file.WriteLine("	End Sub")
       	file.WriteLine("")
       	file.WriteLine("	Public Sub Delete(id)")
       	file.WriteLine("		dim sql : sql = ""DELETE FROM ["& fixedTableName & "] WHERE ["& PrimaryKeyDictionary(tableName) & "] = ?""")
       	file.WriteLine("		DAL.Execute sql, id")
       	file.WriteLine("	End Sub") 
        file.WriteLine("End Class")
        file.WriteLine("")
        File.WriteLine("dim " & fixedTableName & "Repository__Singleton")
        File.WriteLine("Function "  & fixedTableName & "Repository()")
        File.WriteLine("	If IsEmpty(" & fixedTableName & "Repository__Singleton) then")
        file.WriteLine("		set " & fixedTableName & "Repository__Singleton = new " & fixedTableName & "Repository_Class")
        file.WriteLine("	End If")
        file.WriteLine("	set " & fixedTableName & "Repository = " & fixedTableName & "Repository__Singleton")
        file.WriteLine("End Function")
        
        file.WriteLine("%>")
        file.Close
       
       Set file = fso.CreateTextFile(ScriptDirectory()& "ViewModels\" & fixedTableName & "ViewModels.asp",True)
        file.WriteLine("<%")
        file.WriteLine("Class PagedIndex_ViewModel_Class")
        file.WriteLine("		Public Title")
        file.WriteLine("		Public " & fixedTableName)
        file.WriteLine("")
        file.WriteLine("		Public CurrentPageNumber")
        file.WriteLine("		Public PageSize")
        file.WriteLine("		Public PageCount")
        file.WriteLine("		Public RecordCount")
        file.WriteLine("End Class")
        file.WriteLine("")
        file.WriteLine("Class Edit_ViewModel_Class")
        file.WriteLine("		Public Title")
       	file.WriteLine("		Public " & fixedTableName)
        file.WriteLine("")
        file.WriteLine("End Class")
        file.WriteLine("")	
        file.WriteLine("Class Create_ViewModel_Class")
        	For Each fieldName In fieldNamesArray
        	If Not fieldName = PrimaryKeyDictionary(tableName) then
        	file.WriteLine("		Public " & fieldName)  
        	End If
        	Next
        file.WriteLine("End Class")
        file.WriteLine("")
        file.WriteLine("Class Delete_ViewModel_Class")
        file.WriteLine("		Public Title")
        file.WriteLine("		Public " & fixedTableName )
        file.WriteLine("End Class")
        file.WriteLine("")       
        file.WriteLine("%>")
		file.Close
        
        Set file = fso.CreateTextFile(ScriptDirectory()& "Controllers\" & fixedTableName & "\" & fixedTableName & "Controller.asp",True)
        file.WriteLine("<% Option Explicit %>")
        file.WriteLine("<!--#include file=""../../include_all.asp""-->")
        file.WriteLine("<!--#include file=""../../ViewModels/" & fixedTableName & "ViewModels.asp""-->")
        file.WriteLine("<%")
        file.WriteLine("Class " & fixedTableName & "Controller")
        file.WriteLine("	Public Model")
        file.WriteLine("")
        file.WriteLine("	Public Sub Index")
        file.WriteLine("")
        file.WriteLine("		dim page_size : page_size = 10")
        file.WriteLine("		dim page_num  : page_num  = Choice(Len(Request.Querystring(""page_num"")) > 0, Request.Querystring(""page_num""), 1)")
        file.WriteLine("		dim page_count, record_count")
        file.WriteLine("		set Model                   = new PagedIndex_ViewModel_Class")
        file.WriteLine("		Model.Title                 = """ & tableName & """")
        file.WriteLine("		set Model." & fixedTableName & "          = " & fixedTableName & "Repository.FindPaged(empty, """ & PrimaryKeyDictionary(tableName) & """, page_size, page_num, page_count, record_count)")
        file.WriteLine("		Model.CurrentPageNumber     = page_num")
        file.WriteLine("		Model.PageSize              = page_size")
        file.WriteLine("		Model.PageCount             = page_count")
        file.WriteLine("		Model.RecordCount           = record_count")
        file.WriteLine("		%> <!--#include file=""../../Views/" & fixedTableName & "/Index.asp""--> <%")
        file.WriteLine("")
        file.WriteLine("	End Sub")
        file.WriteLine("	Public Sub Search")
        file.WriteLine("")
        file.WriteLine("    	dim searchValue:searchValue = Choice(Request.Form.Count = 0,Request.QueryString(""q""),Request.Form(""q""))")
        file.WriteLine("		dim page_size : page_size = 10")
        file.WriteLine("		dim page_num  : page_num  = Choice(Len(Request.Querystring(""page_num"")) > 0, Request.Querystring(""page_num""), 1)")
        file.WriteLine("		dim page_count, record_count")
        file.WriteLine("		set Model                   = new PagedIndex_ViewModel_Class")
        file.WriteLine("		Model.Title                 = """ & tableName & """")
        file.WriteLine("		set Model." & fixedTableName & "          = " & fixedTableName & "Repository.SearchTablePaged(Array(""" & Join (fieldNamesArray,""",""%"" & searchValue & ""%"",""") & """,""%"" & searchValue & ""%""),""" & PrimaryKeyDictionary(tableName) & """, page_size, page_num, page_count, record_count)")
        file.WriteLine("		Model.CurrentPageNumber     = page_num")
        file.WriteLine("		Model.PageSize              = page_size")
        file.WriteLine("		Model.PageCount             = page_count")
        file.WriteLine("		Model.RecordCount           = record_count")
        file.WriteLine("		%> <!--#include file=""../../Views/" & fixedTableName & "/Index.asp""--> <%")
        file.WriteLine("")
        file.WriteLine("	End Sub")
        file.WriteLine("")
        file.WriteLine("	Public Sub Edit")
        file.WriteLine("")
        file.WriteLine("		dim id : id = Request.QueryString(""Id"")")
        file.WriteLine("		set Model = new Edit_ViewModel_Class")
        file.WriteLine("		set Model." & fixedTableName & " = " & fixedTableName & "Repository.FindBy" & PrimaryKeyDictionary(tableName) & "(id)")
        file.WriteLine("		Model.Title = ""Edit " & fixedTableName & """")
        file.WriteLine("		HTMLSecurity.SetAntiCSRFToken """ & fixedTableName & "EditForm""")
        file.WriteLine("		%> <!--#include file=""../../Views/"& fixedTableName &"/Edit.asp""--> <%")
        file.WriteLine("		Flash.Success = """ & fixedTableName & " " & id & " Updated.""")
        file.WriteLine("	End Sub")
        file.WriteLine("")
        file.WriteLine("	Public Sub EditPost")
        file.WriteLine("		MVC.RequirePost")
        File.WriteLine("		HTMLSecurity.OnInvalidAntiCsrfTokenRedirectToActionExt """ & fixedTableName & "EditForm"", Request.Form(""nonce""), ""Edit"", Array(""Id"", Request.Form(""Id""))")
        File.WriteLine("		dim " & PrimaryKeyDictionary(tableName) & " : "  & PrimaryKeyDictionary(tableName) & " = Request.Form(""Id"")")
        File.WriteLine("		dim model : set model = " & fixedTableName & "Repository.FindBy" & PrimaryKeyDictionary(tableName) & "(" & PrimaryKeyDictionary(tableName) & ")")
        File.WriteLine("		set model = Automapper.AutoMap(Request.Form, model)")
		File.WriteLine("		'model.Validate")
		File.WriteLine("		'If model.Validator.HasErrors then")
		File.WriteLine("			FormCache.SerializeForm ""Edit" & fixedTableName & """, Request.Form")
		File.WriteLine("		'	Flash.Errors = model.Validator.Errors")
		File.WriteLine("		'	MVC.RedirectToActionExt ""Edit"", Array(""Id""," & PrimaryKeyDictionary(tableName) & ")")
		File.WriteLine("		'Else")
		File.WriteLine("			" & fixedTableName & "Repository.Update model")
		File.WriteLine("			FormCache.ClearForm ""Edit" & fixedTableName & """")
		File.WriteLine("			Flash.Success = """ & fixedTableName & " updated.""")
		File.WriteLine("			MVC.RedirectToAction ""Index""")
		File.WriteLine("		'End If")
	    file.WriteLine("	End Sub")
        file.WriteLine("")
        file.WriteLine("	Public Sub Create")
        file.WriteLine("")
        file.WriteLine("		dim form_params : set form_params = FormCache.DeserializeForm(""New" & fixedTableName & """)")
        file.WriteLine("		If Not form_params Is Nothing then")
        file.WriteLine("			set Model = Automapper.AutoMap(form_params, New Create_ViewModel_Class)")
        file.WriteLine("		Else")
        file.WriteLine("			set Model = new Create_ViewModel_Class")
        file.WriteLine("		End If")
        file.WriteLine("")
        file.WriteLine("  		HTMLSecurity.SetAntiCSRFToken """ & fixedTableName & "CreateForm""")
        file.WriteLine("")
        file.WriteLine("		%> <!--#include file=""../../Views/" & fixedTableName & "/Create.asp""--> <%")
        file.WriteLine("	End Sub")
        file.WriteLine("")
        file.WriteLine("	Public Sub CreatePost")
        file.WriteLine("")
        file.WriteLine("		MVC.RequirePost")
        file.WriteLine("			HtmlSecurity.OnInvalidAntiCSRFTokenRedirectToAction """ & fixedTableName & "CreateForm"", Request.Form(""nonce""), ""Create""")
        file.WriteLine("")
        file.WriteLine("			dim new_" & fixedTableName & "_model : set new_" & fixedTableName & "_model = Automapper.AutoMap(Request.Form, new " & fixedTableName & "Model_Class)")	
        file.WriteLine("")
        file.WriteLine("			'new_" & fixedTableName & "_model.Validator.Validate")
        file.WriteLine("")
        file.WriteLine("			'If new_" & fixedTableName & "_model.Validator.HasErrors then")
        file.WriteLine("			'	FormCache.SerializeForm ""New" & fixedTableName & """, Request.Form")
        file.WriteLine("			'	Flash.Errors = new_" & fixedTableName & "_model.Validator.Errors")
        file.WriteLine("			'	MVC.RedirectToAction ""Create""")
        file.WriteLine("			'Else")
        file.WriteLine("				" & fixedTableName & "Repository.AddNew new_" & fixedTableName & "_model")
        File.WriteLine("			'	FormCache.ClearForm ""New" & fixedTableName & """")
        File.WriteLine("				Flash.Success = """ & fixedTableName & " added.""")
        File.WriteLine("				MVC.RedirectToAction ""Index""")
        File.WriteLine("			'End If")
        file.WriteLine("	End Sub")
        file.WriteLine("")
        file.WriteLine("	Public Sub Delete")
        file.WriteLine("		dim id : id = Request.QueryString(""Id"")")
        file.WriteLine("		set Model = new Delete_ViewModel_Class")
        file.WriteLine("		set Model." & fixedTableName & " = " & fixedTableName & "Repository.FindBy" & PrimaryKeyDictionary(tableName) & "(id)")
        file.WriteLine("			Model.Title = ""Delete " & fixedTableName & """")
        file.WriteLine("")
        file.WriteLine("		HTMLSecurity.SetAntiCSRFToken """ & fixedTableName & "DeleteForm""")
        file.WriteLine("")
        file.WriteLine("		%> <!--#include file=""../../Views/" & fixedTableName & "/Delete.asp""--> <%")
        file.WriteLine("	End Sub")
        file.WriteLine("")
        file.WriteLine("	Public Sub DeletePost")
        file.WriteLine("			MVC.RequirePost")
        file.WriteLine("			HtmlSecurity.OnInvalidAntiCSRFTokenRedirectToAction """ & fixedTableName & "DeleteForm"", Request.Form(""nonce""), ""Create""")
        file.WriteLine("")
        file.WriteLine("			dim id : id = Request.Form(""Id"")")
        file.WriteLine("			" & fixedTableName & "Repository.Delete id")
        file.WriteLine("")
        file.WriteLine("			Flash.Success = """ & fixedTableName & " deleted.""")
        file.WriteLine("			MVC.RedirectToAction ""Index""") 
        file.WriteLine("	End Sub")
        file.WriteLine("")
        file.WriteLine("End Class")
        file.WriteLine("MVC.Dispatch")
        file.WriteLine("%>")
        file.Close
	
    	Set file = fso.CreateTextFile(ScriptDirectory()& "Views\" & fixedTableName & "\edit.asp",True)
    	file.WriteLine("<h2><%= H(Model.Title) %></h2>")
    	file.WriteLine("<%= HTML.FormTag("""& tableName & """, ""EditPost"", empty, empty) %>")
    	file.WriteLine("	<%= HTML.Hidden(""nonce"", HTMLSecurity.GetAntiCSRFToken(""" & fixedTableName & "EditForm"")) %>")
    	file.WriteLine("	<%= HTML.Hidden(""Id"", Model." & fixedTableName & "." & PrimaryKeyDictionary(tableName) & ") %>")
    		For Each field In fieldNamesArray
    		If Not field = PrimaryKeyDictionary(tableName) then
    			file.WriteLine("	<div class=""row"">")
    			file.WriteLine("		<div class=""col-md-4"">")
    			file.WriteLine("			<div class=""form-group"">")
    			file.WriteLine("				<label for=""" & field & """>" & field & "</label>")
    			file.WriteLine("				<%= HTML.TextboxExt(""" & field & """, Model." & fixedTableName & "." & field & ", Array(""class"", ""form-control"")) %>")
    			file.WriteLine("			</div>")
    			file.WriteLine("		</div>")
    			file.WriteLine("	</div>")
    			End if
    		Next
    	file.WriteLine("<hr />")
    	file.WriteLine("<div class=""form-group"">")
    	file.WriteLine("	<% = HTML.Button(""submit"", ""<i class='glyphicon glyphicon-ok'></i> Save"", ""btn-primary"") %>")
    	
     	file.WriteLine("	   			&nbsp;&nbsp;")
		file.WriteLine("				<%= HTML.LinkToExt(""<i class='glyphicon glyphicon-remove'></i> Delete"", """ & fixedTableName & """, ""Delete"", Array(""id"", Model." & fixedTableName & "." & PrimaryKeyDictionary(tableName) & "), Array(""class"", ""btn btn-danger"")) %>")
		file.WriteLine("				&nbsp;&nbsp;")
		file.WriteLine("				<%= HTML.LinkToExt(""Cancel"", """ & fixedTableName & """, ""Index"", empty, Array(""class"", ""btn btn-default"")) %>")
    	file.WriteLine("</div>")
    	file.WriteLine("</form>")
    	file.Close   
        Set file = fso.CreateTextFile(ScriptDirectory()& "Views\" & fixedTableName & "\index.asp",True)
        file.WriteLine("<h2><%= H(Model.Title) %></h2>")
        file.WriteLine("<div class=""row"">")
        file.WriteLine("	<div class=""col-md-8 col-sm-8 col-xs-12"">")
        file.WriteLine("		<%= H(Model.RecordCount) %> " & tableName & " found. Showing <%= H(Model.PageSize) %> records per page.")
        file.WriteLine("		<%= HTML.LinkToExt(""<i class='bi bi-plus-square-fill'></i> New"",""" & fixedTableName & """, ""Create"", empty, Array(""class"", ""btn btn-xs btn-primary"")) %>")
        file.WriteLine("	</div>")
        file.WriteLine("            <div class=""col-md-4 col-sm-4 col-xs-12"">")
		file.WriteLine("")
		file.WriteLine("	    <%= HTML.FormTag(""" & fixedTableName & """, ""Search"", empty, empty) %>")
		file.WriteLine("")
		file.WriteLine("	        <div class=""col-md-10 col-sm-10 col-xs-12"">")
		file.WriteLine("		        <label class=""sr-only"" for=""search"">Search</label>")
		file.WriteLine("		            <div class=""input-group"">")
		file.WriteLine("			            <input type=""text"" class=""form-control input-search"" value='<%= Choice(Request.Form.Count = 0,Request.QueryString(""q""),Request.Form(""q"")) %>' name=""q"" id=""search"" placeholder=""Search"">")
		file.WriteLine("			            <span class=""input-group-addon group-icon""><span class=""glyphicon glyphicon-eye-open""></span>")
        file.WriteLine("                        <button type=""submit"" class=""btn btn-success""><i class=""bi bi-search""></i>Search</buttton>")
		file.WriteLine("		            </div>")
		file.WriteLine("	        </div>")
		file.WriteLine("")	
        file.WriteLine("        </form>")
        file.WriteLine("    </div>")
		file.WriteLine("</div>")
		file.WriteLine("<table id=""" & fixedTableName & """ class=""table table-striped"">")
    	file.WriteLine("	<thead>")
        file.WriteLine("		<tr>")
        file.WriteLine("			<th></th>")
        
        	For Each field In fieldNamesArray
        file.WriteLine("			<th style=""text-align: left"">" & field & "</th>")
        	Next
        	
        file.WriteLine("			<th></th>")
        file.WriteLine("		</tr>")
    	file.WriteLine("	</thead>")
    	file.WriteLine("<tbody>")
		file.WriteLine("        <% dim it : set it = Model." & fixedTableName & ".Iterator %>")
		file.WriteLine("			<% dim " & fixedTableName & " %>")
		file.WriteLine("			<% While it.HasNext %>")
		file.WriteLine("				<% set " & fixedTableName & " = it.GetNext() %>")
		file.WriteLine("				<tr>")
		file.WriteLine("					<td>")
		file.WriteLine("						<%= HTML.LinkToExt(""<i class='bi bi-search'></i>"", """& fixedTableName &""", ""Edit"", Array(""Id"", " & fixedTableName & "." & PrimaryKeyDictionary(tableName) & "), Array(""class"", ""btn btn-primary"")) %>")	
		file.WriteLine("					</td>")
		        	
		        	For Each field In fieldNamesArray
        				file.WriteLine("			<td><% = H(" & fixedTableName & "." & field &") %></td>")
        			Next
		file.WriteLine("</tr>")
		file.WriteLine("					<% Wend %>")
		file.WriteLine("    </tbody>")
		file.WriteLine("</table>")
		file.WriteLine("		<div>")
		file.WriteLine("    <% If Model.CurrentPageNumber <> 1 then %>")
		file.WriteLine("        <%= HTML.LinkToExt(""<i class='bi bi-chevron-left'></i><i class='bi bi-chevron-left'></i>"", MVC.ControllerName, MVC.ActionName, Array(""page_num"", 1,""q"", Choice(Request.Form.Count = 0,Request.QueryString(""q""),Request.Form(""q""))), Array(""class"", ""btn btn-default"")) %>")
		file.WriteLine("        &nbsp;")
		file.WriteLine("        <%= HTML.LinkToExt(""<i class='bi bi-chevron-left'></i>"", MVC.ControllerName, MVC.ActionName, Array(""page_num"", Model.CurrentPageNumber - 1,""q"", Choice(Request.Form.Count = 0,Request.QueryString(""q""),Request.Form(""q""))), Array(""class"", ""btn btn-default"")) %>")
        		file.WriteLine("&nbsp;")
		file.WriteLine("    <% Else %>")
		file.WriteLine("        <a class='btn btn-default disabled'><i class='bi bi-chevron-left'></i><i class='bi bi-chevron-left'></i></a>")
		file.WriteLine("        &nbsp;")
		file.WriteLine("        <a class='btn btn-default disabled'><i class='bi bi-chevron-left'></i></a>")
		file.WriteLine("        &nbsp; ")
		file.WriteLine("    <% End If %>")

		file.WriteLine("    <% If CInt(Model.CurrentPageNumber) < CInt(Model.PageCount) then %>")
 		file.WriteLine("       <%= HTML.LinkToExt(""<i class='bi bi-chevron-right'></i>"", MVC.ControllerName, MVC.ActionName, Array(""page_num"", Model.CurrentPageNumber + 1,""q"", Choice(Request.Form.Count = 0,Request.QueryString(""q""),Request.Form(""q""))), Array(""class"", ""btn btn-default"")) %>")
 		file.WriteLine("       &nbsp;")
 		file.WriteLine("       <%= HTML.LinkToExt(""<i class='bi bi-chevron-right'></i><i class='bi bi-chevron-right'></i>"", MVC.ControllerName, MVC.ActionName, Array(""page_num"", Model.PageCount,""q"", Choice(Request.Form.Count = 0,Request.QueryString(""q""),Request.Form(""q""))), Array(""class"", ""btn btn-default"")) %>")
 		file.WriteLine("       &nbsp;")
		file.WriteLine("    <% Else %>")
		file.WriteLine("        <a class='btn btn-default disabled'><i class='bi bi-chevron-right'></i><i class='bi bi-chevron-right'></i></a>")
		file.WriteLine("        &nbsp;")
		file.WriteLine("        <a class='btn btn-default disabled'><i class='bi bi-chevron-right'></i></a>")
		file.WriteLine("        &nbsp; ")
    		file.WriteLine("<% End If %>")
		file.WriteLine("</div>")


		file.WriteLine("</div>")
		
        file.Close
        
        Set file = fso.CreateTextFile(ScriptDirectory()& "Views\" & fixedTableName & "\create.asp",True)
        file.WriteLine("<h2>Create " & fixedTableName &"</h2>")
        file.WriteLine("")
        file.WriteLine("<%= HTML.FormTag(""" & fixedTableName &""", ""CreatePost"", empty, empty) %>")
        file.WriteLine("<%= HTML.Hidden(""nonce"", HTMLSecurity.GetAntiCSRFToken("""& fixedTableName & "CreateForm"")) %>")
        file.WriteLine("<hr />")
		file.WriteLine("")
    	file.WriteLine("<div class=""form-group"">")
    		For Each field In fieldNamesArray
    		If Not field = PrimaryKeyDictionary(tableName) then
                file.WriteLine("	<div class=""row"">")
            	file.WriteLine("		<div class=""col-md-4"">")
    			file.WriteLine("			<div class=""form-group"">")
    			file.WriteLine("				<label for=""" & field & """>" & field & "</label>")
    			file.WriteLine("				<%= HTML.TextboxExt(""" & field & """, Model." & field & ", Array(""class"", ""form-control"")) %>")
    			file.WriteLine("			</div>")
    			file.WriteLine("		</div>")
    			file.WriteLine("	</div>")
    			End if
    		Next
    	file.WriteLine("    <%= HTML.Button(""submit"", ""<i class='glyphicon glyphicon-ok'></i> Create"", ""btn-primary"") %>")
    	file.WriteLine("    &nbsp;&nbsp;")
    	file.WriteLine("    <%= HTML.LinkToExt(""<i class='glyphicon glyphicon-remove'></i> Cancel"", """ & fixedTableName & """, ""Index"", empty, Array(""class"", ""btn btn-default"")) %>")
   
    	file.WriteLine("</div>")
		file.WriteLine("")
		file.WriteLine("</form>")
        
        file.Close
        Set file = fso.CreateTextFile(ScriptDirectory()& "Views\" & fixedTableName & "\delete.asp",True)        
        file.WriteLine("<h2><%= H(Model.Title) %></h2>")
        file.WriteLine("")
        file.WriteLine("<p class=""alert alert-danger"">Are you sure you want to delete this " & fixedTableName & "?</p>")
        file.WriteLine("")
        file.WriteLine("<%= HTML.FormTag(""" & fixedTableName & """, ""DeletePost"", empty, Array(""class"", ""form-horizontal"")) %>")
        file.WriteLine("<%= HTML.Hidden(""nonce"", HTMLSecurity.GetAntiCSRFToken(""" & fixedTableName & "DeleteForm"")) %>")
    	file.WriteLine("<%= HTML.Hidden(""Id"", Model." & fixedTableName & "." & PrimaryKeyDictionary(tableName) & ") %>")
        file.WriteLine("<div class=""col-md-10"">")
        file.WriteLine("<div class=""form-group"">")
        file.WriteLine("     <%= HTML.Button(""submit"", ""<i class='glyphicon glyphicon-remove'></i> Confirm Delete"", ""btn-danger"") %>")
        file.WriteLine("    &nbsp;&nbsp;")
        file.WriteLine("     <%= HTML.LinkToExt(""Cancel"", """ & fixedTableName & """, ""Index"", empty, Array(""class"", ""btn btn-success"")) %>")

        For Each field In fieldNamesArray
        If Not field = PrimaryKeyDictionary(tableName) Then
                file.WriteLine("	<div class=""row"">")
            	file.WriteLine("		<div class=""col-md-4"">")
    			file.WriteLine("			<div class=""form-group"">")
    			file.WriteLine("				<label for=""" & field & """>" & field & "</label>")
    			file.WriteLine("				<%= HTML.TextboxExt(""" & field & """, Model." & fixedTableName & "." & field & ", Array(""class"", ""form-control"")) %>")
    			file.WriteLine("			</div>")
    			file.WriteLine("		</div>")
    			file.WriteLine("	</div>")
    	End If
        Next

        file.WriteLine(" </div>")
        file.WriteLine("</div>")
        file.WriteLine("</form>")
       
       
       
        file.Close
        Set objFile = fso.OpenTextFile(ScriptDirectory() & "Views\Shared\layout.header.asp",1)
        	headerHtml = objFile.ReadAll()
        	objFile.Close
        	
        	dropDownLinks = "<li role=""presentation"" class=""dropdown"">" &_
        	"    <a class=""dropdown-toggle"" data-toggle=""dropdown"" href=""#"" role=""button"" aria-haspopup=""true"" aria-expanded=""false"">" &_
        	"      Dropdown <span class=""caret""></span></a>" &_
        	""
        	
        	If InStr(headerHtml,"<li class=""nav-item""><%= Html.LinkTOExt(""" & tableName & """,""" & fixedTableName & """,""Index"",empty,Array(""Class"",""nav-link"")) %></li>") = 0 then
        		newHeaderHtml = Replace(headerHtml,"<!--nav bar placeholder-->","						<li class=""nav-item""><%= Html.LinkTOExt(""" & tableName & """,""" & fixedTableName & """,""Index"",empty,Array(""Class"",""nav-link"")) %></li>" & vbCrLf & "<!--nav bar placeholder-->")
        		Set objFile = fso.OpenTextFile(ScriptDirectory() & "Views\Shared\layout.header.asp",2)
        		objFile.WriteLine newHeaderHtml
        		
        	End If
        	objFile.Close
        
        
        
        props.Clear
        rs.MoveNext
       
        Else
        rs.MoveNext
       
        End if
       
Loop
includedFile.Close
WScript.Quit

Sub includeFile(fSpec)
    executeGlobal CreateObject("Scripting.FileSystemObject").openTextFile(IncludeDirectory & fSpec & ".vbs").readAll()
End Sub

Function PrimaryKeysFromADOConnectionToDictionary(ADOConn)
Dim rstSchema
Dim returnDictionary

	If TypeName(ADOConn) = "Connection" Then
		Set rstSchema = oConn.OpenSchema(adSchemaPrimaryKeys)
		Set rstableNames = oConn.OpenSchema(20,Array(Empty, Empty, Empty, "Table"))
		Set returnDictionary = WScript.CreateObject("scripting.dictionary")			
			
			While Not rstSchema.EOF 
				If returnDictionary.Exists(rstSchema.Fields("TABLE_NAME").Value) = false Then		
		 			returnDictionary.Add rstSchema.Fields("TABLE_NAME").Value,rstSchema.Fields("COLUMN_NAME").Value	
		 		End If
		 		rstSchema.MoveNext	 	
		 	Wend
	rstSchema.Close
	End If 
	
	Set PrimaryKeysFromADOConnectionToDictionary = returnDictionary
End Function

Sub Init

MsgBox(oConn.State)
If oConn.State = 0 Then
oConn.Open()
'End If
Set PrimaryKeyDictionary = PrimaryKeysFromADOConnectionToDictionary(oConn)
If Not fso.FolderExists(ScriptDirectory()& "DomainModels\") Then fso.CreateFolder(ScriptDirectory()& "DomainModels\")
If Not fso.FolderExists(ScriptDirectory()& "ViewModels\") Then fso.CreateFolder(ScriptDirectory()& "ViewModels\")
If Not fso.FolderExists(ScriptDirectory()& "Controllers\") Then fso.CreateFolder(ScriptDirectory()& "Controllers\")
If Not fso.FolderExists(ScriptDirectory()& "Views\") Then fso.CreateFolder(ScriptDirectory()& "Views\")

Set includedFile = fso.CreateTextFile(ScriptDirectory()& "include_all.asp",True)
includedFile.WriteLine("<!--#include file=""../MVC/lib.all.asp""-->")
includedFile.WriteLine("<!--#include file=""DAL/lib.DAL.asp""-->")
includedFile.WriteLine("<!--#include file=""app.Config.asp""-->")

Set rs = oConn.OpenSchema(20,Array(Empty, Empty, Empty, "Table"))
End If


End Sub 


Sub InitFieldNameIterator
        	Dim cmd
        	Set cmd = WScript.CreateObject("ADODB.COMMAND")
        	cmd.ActiveConnection = oConn
        	cmd.CommandText = "Select * From [" & tableName & "]"
        Set FieldsRs =  cmd.Execute()
        Set fields = FieldsRs.Fields
        
      Set props = New Stack
  
 
        	For Each Field In FieldsRs.Fields
        		props.Push(Field.Name)
        		file.WriteLine ("	Public " & Field.Name & " '" & Field.Attributes)
        	Next
        FieldsRs.Close	

        If Not PrimaryKeyDictionary.Exists(tableName) Then
        	PrimaryKeyDictionary.Add tableName,props.ToArray()(0)
        End If
End Sub
