Shader uniforms not showing up - opengl

I can not get this shader to return its uniforms.
I have looked everywhere for a possible problem with my shader assembler or bindings. I even rebooted my machine (desktop quad core) thinking maybe the OpenGL driver crapped out.
Here's the code that tries but fails to get the uniform locations:
Private Sub set_deferredLighting_variables()
deferred_cam_position = Gl.glGetUniformLocation(shader_list.deferred_shader, "viewPos")
deferred_light_position = Gl.glGetUniformLocation(shader_list.deferred_shader, "Light_position")
deferred_gcolor = Gl.glGetUniformLocation(shader_list.deferred_shader, "gColor")
deferred_gnormal = Gl.glGetUniformLocation(shader_list.deferred_shader, "gNormal")
deferred_gposition = Gl.glGetUniformLocation(shader_list.deferred_shader, "gPosition")
End Sub
And here is the fragment shader:
#version 330 core
in vec2 TexCoords;
out vec4 FragColor;
uniform sampler2D gPosition;
uniform sampler2D gNormal;
uniform sampler2D gColor;
uniform vec3 Light_position;
uniform vec3 viewPos;
void main()
{
vec3 light_Color = vec3 (1.0, 1.0, 0.9);
// Retrieve data from G-buffer
vec3 FragPos = texture(gPosition, TexCoords).rgb;
vec3 Normal = texture(gNormal, TexCoords).rgb;
vec3 Albedo = texture(gColor, TexCoords).rgb;
float Specular = texture(gNormal, TexCoords).a;
// Then calculate lighting as usual
vec3 lighting = Albedo * 0.1; // hard-coded ambient component
vec3 viewDir = normalize(viewPos - FragPos);
// Diffuse
vec3 lightDir = normalize(Light_position - FragPos);
vec3 diffuse = max(dot(Normal, lightDir), 0.0) * Albedo * light_Color;
FragColor = vec4(lighting + diffuse, 1.0);
}
For the life of me I can't find a reason why the uniforms are not showing up.
I have a very very good shader assembler that checks at every stage for the status and any glGetError. If glGetError returns anything but 0, it throws up a message box. My assembler reads and builds the shaders in the folder.. Naming of the shaders is critical. The assembler builds 20+ shaders with no problem including this one.. There are absolutely no errors thrown!
I had this issue once a few months back and rebooting fixed the problem.. I tried that.. No luck.
Any help would be fantastic!
Here is the shader assembler code: Not how crazy I am at checking every thing.
Public Function assemble_shader(v As String, g As String, f As String, ByRef shader As Integer, ByRef name As String, ByRef has_geo As Boolean) As Integer
Dim vs(1) As String
Dim gs(1) As String
Dim fs(1) As String
Dim vertexObject As Integer
Dim geoObject As Integer
Dim fragmentObject As Integer
Dim status_code As Integer
Dim info As New StringBuilder
info.Length = 1024
Dim info_l As Integer
If shader > 0 Then
Gl.glUseProgram(0)
Gl.glDeleteProgram(shader)
Gl.glGetProgramiv(shader, Gl.GL_DELETE_STATUS, status_code)
Gl.glFinish()
End If
Dim e = Gl.glGetError
If e <> 0 Then
Dim s = Glu.gluErrorString(e)
Dim ms As String = System.Reflection.MethodBase.GetCurrentMethod().Name
'MsgBox("Function: " + ms + vbCrLf + "Error! " + s, MsgBoxStyle.Exclamation, "OpenGL Issue")
End If
'have a hard time with files remaining open.. hope this fixes it! (yep.. it did)
Using vs_s As New StreamReader(v)
vs(0) = vs_s.ReadToEnd
vs_s.Close()
vs_s.Dispose()
End Using
Using fs_s As New StreamReader(f)
fs(0) = fs_s.ReadToEnd
fs_s.Close()
fs_s.Dispose()
End Using
If has_geo Then
Using gs_s As New StreamReader(g)
gs(0) = gs_s.ReadToEnd
gs_s.Close()
gs_s.Dispose()
End Using
End If
vertexObject = Gl.glCreateShader(Gl.GL_VERTEX_SHADER)
fragmentObject = Gl.glCreateShader(Gl.GL_FRAGMENT_SHADER)
'--------------------------------------------------------------------
shader = Gl.glCreateProgram()
' Compile vertex shader
Gl.glShaderSource(vertexObject, 1, vs, vs(0).Length)
Gl.glCompileShader(vertexObject)
Gl.glGetShaderInfoLog(vertexObject, 8192, info_l, info)
Gl.glGetShaderiv(vertexObject, Gl.GL_COMPILE_STATUS, status_code)
If Not status_code = Gl.GL_TRUE Then
Gl.glDeleteShader(vertexObject)
gl_error(name + "_vertex didn't compile!" + vbCrLf + info.ToString)
'Return
End If
e = Gl.glGetError
If e <> 0 Then
Dim s = Glu.gluErrorString(e)
Dim ms As String = System.Reflection.MethodBase.GetCurrentMethod().Name
MsgBox("Function: " + ms + vbCrLf + "Error! " + s, MsgBoxStyle.Exclamation, "OpenGL Issue")
End If
If has_geo Then
'geo
geoObject = Gl.glCreateShader(Gl.GL_GEOMETRY_SHADER_EXT)
Gl.glShaderSource(geoObject, 1, gs, gs(0).Length)
Gl.glCompileShader(geoObject)
Gl.glGetShaderInfoLog(geoObject, 8192, info_l, info)
Gl.glGetShaderiv(geoObject, Gl.GL_COMPILE_STATUS, status_code)
If Not status_code = Gl.GL_TRUE Then
Gl.glDeleteShader(geoObject)
gl_error(name + "_geo didn't compile!" + vbCrLf + info.ToString)
'Return
End If
e = Gl.glGetError
If e <> 0 Then
Dim s = Glu.gluErrorString(e)
Dim ms As String = System.Reflection.MethodBase.GetCurrentMethod().Name
MsgBox("Function: " + ms + vbCrLf + "Error! " + s, MsgBoxStyle.Exclamation, "OpenGL Issue")
End If
Gl.glProgramParameteriEXT(shader, Gl.GL_GEOMETRY_INPUT_TYPE_EXT, Gl.GL_TRIANGLES)
Gl.glProgramParameteriEXT(shader, Gl.GL_GEOMETRY_OUTPUT_TYPE_EXT, Gl.GL_LINE_STRIP)
If name.Contains("normal") Then
Gl.glProgramParameteriEXT(shader, Gl.GL_GEOMETRY_VERTICES_OUT_EXT, 18)
Else
Gl.glProgramParameteriEXT(shader, Gl.GL_GEOMETRY_VERTICES_OUT_EXT, 4) 'leaf needs 4
End If
e = Gl.glGetError
If e <> 0 Then
Dim s = Glu.gluErrorString(e)
Dim ms As String = System.Reflection.MethodBase.GetCurrentMethod().Name
MsgBox("Function: " + ms + vbCrLf + "Error! " + s, MsgBoxStyle.Exclamation, "OpenGL Issue")
End If
End If
' Compile fragment shader
Gl.glShaderSource(fragmentObject, 1, fs, fs(0).Length)
Gl.glCompileShader(fragmentObject)
Gl.glGetShaderInfoLog(fragmentObject, 8192, info_l, info)
Gl.glGetShaderiv(fragmentObject, Gl.GL_COMPILE_STATUS, status_code)
If Not status_code = Gl.GL_TRUE Then
Gl.glDeleteShader(fragmentObject)
gl_error(name + "_fragment didn't compile!" + vbCrLf + info.ToString)
'Return
End If
e = Gl.glGetError
If e <> 0 Then
Dim s = Glu.gluErrorString(e)
Dim ms As String = System.Reflection.MethodBase.GetCurrentMethod().Name
MsgBox("Function: " + ms + vbCrLf + "Error! " + s, MsgBoxStyle.Exclamation, "OpenGL Issue")
End If
'attach shader objects
Gl.glAttachShader(shader, fragmentObject)
If has_geo Then
Gl.glAttachShader(shader, geoObject)
End If
Gl.glAttachShader(shader, vertexObject)
'link program
Gl.glLinkProgram(shader)
' detach shader objects
Gl.glDetachShader(shader, fragmentObject)
If has_geo Then
Gl.glDetachShader(shader, geoObject)
End If
Gl.glDetachShader(shader, vertexObject)
e = Gl.glGetError
If e <> 0 Then
Dim s = Glu.gluErrorString(e)
Dim ms As String = System.Reflection.MethodBase.GetCurrentMethod().Name
MsgBox("Function: " + ms + vbCrLf + "Error! " + s, MsgBoxStyle.Exclamation, "OpenGL Issue")
End If
Gl.glGetShaderiv(shader, Gl.GL_LINK_STATUS, status_code)
If Not status_code = Gl.GL_TRUE Then
Gl.glDeleteProgram(shader)
gl_error(name + " did not link!" + vbCrLf + info.ToString)
'Return
End If
'delete shader objects
Gl.glDeleteShader(fragmentObject)
Gl.glGetShaderiv(fragmentObject, Gl.GL_DELETE_STATUS, status_code)
If has_geo Then
Gl.glDeleteShader(geoObject)
Gl.glGetShaderiv(geoObject, Gl.GL_DELETE_STATUS, status_code)
End If
Gl.glDeleteShader(vertexObject)
Gl.glGetShaderiv(vertexObject, Gl.GL_DELETE_STATUS, status_code)
e = Gl.glGetError
If e <> 0 Then
'aways throws a error after deletion even though the status shows them as deleted.. ????
Dim s = Glu.gluErrorString(e)
Dim ms As String = System.Reflection.MethodBase.GetCurrentMethod().Name
'MsgBox("Function: " + ms + vbCrLf + "Error! " + s, MsgBoxStyle.Exclamation, "OpenGL Issue")
End If
vs(0) = Nothing
fs(0) = Nothing
If has_geo Then
gs(0) = Nothing
End If
GC.Collect()
GC.WaitForFullGCComplete()
Return shader
End Function

Related

Lotka-Volterra Models in Swift 3

I am trying to implement an rk4 function to solve 2 differential equations. I have this code that implements the Runge Kutta 4 method:
//RK4 method
func rk4_func(y_array: [Double], f_array: [(([Double], Double) -> Double)], t_val: Double, h_val: Double) -> [Double] {
let length = y_array.count
let t_half_step = t_val + h_val / 2.0
let t_step = t_val + h_val
var k1 = [Double](repeating: 0.0, count: length)
var k2 = [Double](repeating: 0.0, count: length)
var k3 = [Double](repeating: 0.0, count: length)
var k4 = [Double](repeating: 0.0, count: length)
var w = [Double](repeating: 0.0, count: length)
var result = [Double](repeating: 0.0, count: length)
for i in 0...length {
k1[i] = h_val * f_array[i](y_array, t_val)
w[i] = y_array[i] + k1[i]/2.0
}
for i in 0...length {
k2[i] = h_val * f_array[i](w, t_half_step)
w[i] = y_array[i] + k2[i]/2.0
}
for i in 0...length {
k3[i] = h_val * f_array[i](w, t_half_step)
w[i] = y_array[i] + k3[i]
}
for i in 0...length {
k4[i] = h_val * f_array[i](w, t_step)
}
for i in 0...length {
result[i] = y_array[i] + (k1[i] + 2.0*k2[i] + 2.0*k3[i] + k4[i])/6.0
}
print(result)
return result;
}
But now I need to actually use it, which is the part I'm confused about. If anyone has experience with numerically computing solutions to differential equations, that would help.
What arrays do I need to feed this function?
What does the t_val argument represent? Is it a maximum time?
How does the output "solve" the equation?
What does the output give me?
In the line k1[i] = h_val * f_array[i](y_array, t_val), what does f_array[i](y_array, t_val) mean? Is it saying that for the i-th value of f_array, find the corresponding i-th value for y_array? Then what does the t_val mean there?
For reference, here are the 2 differential equations needed to be solved. The context is that I'm trying to numerically solve these Lotka-Volterra Models to plot a time series and a phase space plot in Xcode (Swift 3.x).
y is the vector of the current state (implemented as double array). f_array is a function pointer to a function doty = f_array(y,t).
t_val is the time for the current state, h_val is the time step.
One call of rk4_func performs the time step from t_val to t_val+h_val and
returns the new state, y_next = rk4_func(y, f_array, t, h).
One would have to study the language internals. Hopefully, that is, for the code to work correctly, the first call of f_array[0](y_array, t_val) computes the full vector/array-valued result and further calls just extract the components of the cached result.
The original code as found at https://github.com/pdemarest/swift-rk4 is severely deficient in its RK4 realization and out-of-date in language standards. A working version as tested at https://swift.sandbox.bluemix.net/ is
import Foundation
func RK4step(y: [Double], f: ([Double], Double) -> [Double], t: Double, h: Double) -> [Double] {
let length = y.count
var w = [Double](repeating: 0.0, count: length )
var result = [Double](repeating: 0.0, count: length)
let k1 = f(y,t)
assert(k1.count == y.count, "States and Derivatives must be the same length")
for i in 0..<length { w[i] = y[i] + 0.5*h*k1[i] }
let k2 = f(w, t+0.5*h)
for i in 0..<length { w[i] = y[i] + 0.5*h*k2[i] }
let k3 = f(w,t+0.5*h)
for i in 0..<length { w[i] = y[i] + h*k3[i]
}
let k4 = f(w,t+h)
for i in 0..<length {
result[i] = y[i] + (k1[i] + 2.0*k2[i] + 2.0*k3[i] + k4[i])*h/6.0
}
return result;
}
func test_exp(){
// Integrate: y' = y
// y_0 = 1.0
// from 0 to 2.0
var y = [1.0]
func deriv (y: [Double], t: Double) -> [Double] {
return [ y[0] ]
}
var t = 0.0
let h = 0.1
while t < 2.0 {
y = RK4step(y:y, f:deriv, t:t, h:h)
t += h
print("t: \(t), y: \(y[0]) exact: \(exp(t))\n")
}
let exact = exp(2.0)
let error = abs(y[0] - exact)
assert(error < pow(h, 4.0))
print("y: \(y[0]) exact: \(exact) error: \(error)\n")
}
print("testing...\n")
test_exp()
For the Volterra-Lotka dynamics one would have to change
var y = [150.0, 5.0]
let a = 5.0
let b = 1.0
let eps = 0.1
let m = 5.0
func deriv (y: [Double], t: Double) -> [Double] {
let p = y[0]
let q = y[1]
return [ a*p-b*p*q, eps*b*p*q - m*q ]
}
with properly fixed global constants a,b,eps,m and a two-dimensional initial value. Add print statements where required.

How to stop second run of the code to prevent override data regex vba?

The below code will split 1 cell into 3 or 4 column based on a pattern of 6chr,5chr,4chr,5+chr. The below also needs to be available on all open workbooks and work from the user selection.
How to fix a bug that after the first splitting of the cell is done and by mistake you run it again will override the data?
Class Module
Option Explicit
'Rename this Class Module cFabric
Private pStyle As String
Private pFabric As String
Private pColour As String
Private pSize As String
Public Property Get Style() As String
Style = pStyle
End Property
Public Property Let Style(Value As String)
pStyle = Value
End Property
Public Property Get Fabric() As String
Fabric = pFabric
End Property
Public Property Let Fabric(Value As String)
pFabric = UCase(Value)
End Property
Public Property Get Colour() As String
Colour = pColour
End Property
Public Property Let Colour(Value As String)
pColour = Value
End Property
Public Property Get Size() As String
Size = pSize
End Property
Public Property Let Size(Value As String)
pSize = Value
End Property
Regular Module
Option Explicit
Sub Fabrics()
Dim wsSrc As Workbook, wsRes As Workbook
Dim vSrc As Variant, vRes As Variant, rRes As Range
Dim RE As Object, MC As Object
Const sPat As String = "^(.{6})\s*(.{5})\s*(.{4})(?:.*1/(\S+))?"
'Group 1 = style
'Group 2 = fabric
'Group 3 = colour
'Group 4 = size
Dim colF As Collection, cF As cFabric
Dim I As Long
Dim S As String
Dim V As Variant
'Set source and results worksheets and ranges
Set wsSrc = ActiveWorkbook
Set wsRes = ActiveWorkbook
Set rRes = wsRes.Application.Selection
'Read source data into array
vSrc = Application.Selection
'Initialize the Collection object
Set colF = New Collection
'Initialize the Regex Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = False
.MultiLine = True
.Pattern = sPat
'Test for single cell
If Not IsArray(vSrc) Then
V = vSrc
ReDim vSrc(1 To 1, 1 To 1)
vSrc(1, 1) = V
End If
'iterate through the list
For I = 1 To UBound(vSrc, 1)
S = vSrc(I, 1)
Set cF = New cFabric
If .test(S) = True Then
Set MC = .Execute(S)
With MC(0)
cF.Style = .submatches(0)
cF.Fabric = .submatches(1)
cF.Colour = .submatches(2)
cF.Size = .submatches(3)
End With
Else
cF.Style = S
End If
colF.Add cF
Next I
End With
'create results array
'Exit if no results
If colF.Count = 0 Then Exit Sub
ReDim vRes(1 To colF.Count, 1 To 4)
'Populate the rest
I = 0
For Each V In colF
I = I + 1
With V
vRes(I, 1) = .Style
vRes(I, 2) = .Fabric
vRes(I, 3) = .Colour
vRes(I, 4) = .Size
End With
Next V
'Write the results
Set rRes = rRes.Resize(UBound(vRes, 1), UBound(vRes, 2))
rRes.Value = vRes
End Sub
Credits for the above goes to #Ron Rosenfeld for the project!
One way to tell if the entry has been previously split is as follows
If the regex.test fails, then
If the results line passes, then the item has been previously split
if not, then it is a blank, or a malformed entry
Note that a lot of this could be avoided if you were not overwriting your original data. I would recommend against overwriting your data both for audit and debugging purposes, but the below should help in case you cannot change that.
You just need to make some small changes in the logic where we checked for the malformed entry originally. As well as reading in the "possible" results array into vSrc so that we have the potentially split data to compare:
Option Explicit
Sub Fabrics()
'assume data is in column A
Dim wsSrc As Worksheet, wsRes As Worksheet
Dim vSrc As Variant, vRes As Variant, rRes As Range
Dim RE As Object, MC As Object
Const sPat As String = "^(.{6})\s*(.{5})\s*(.{4})(?:.*1/(\S+))?"
'Group 1 = style
'Group 2 = fabric
'Group 3 = colour
'Group 4 = size
Dim colF As Collection, cF As cFabric
Dim I As Long
Dim S As String
Dim V As Variant
'Set source and results worksheets and ranges
Set wsSrc = ActiveSheet
Set wsRes = ActiveSheet
Set rRes = Selection
'Read source data into array
vSrc = Selection.Resize(columnsize:=4)
'Initialize the Collection object
Set colF = New Collection
'Initialize the Regex Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = False
.MultiLine = True
.Pattern = sPat
'iterate through the list
'Test for single cell
If Not IsArray(vSrc) Then
V = vSrc
ReDim vSrc(1 To 1, 1 To 1)
vSrc(1, 1) = V
End If
For I = 1 To UBound(vSrc, 1)
S = vSrc(I, 1)
Set cF = New cFabric
If .test(S) = True Then
Set MC = .Execute(S)
With MC(0)
cF.Style = .submatches(0)
cF.Fabric = .submatches(1)
cF.Colour = .submatches(2)
cF.Size = .submatches(3)
End With
ElseIf .test(vSrc(I, 1) & vSrc(I, 2) & vSrc(I, 3)) = False Then
cF.Style = S
Else
cF.Style = vSrc(I, 1)
cF.Fabric = vSrc(I, 2)
cF.Colour = vSrc(I, 3)
cF.Size = vSrc(I, 4)
End If
colF.Add cF
Next I
End With
'create results array
'Exit if not results
If colF.Count = 0 Then Exit Sub
ReDim vRes(1 To colF.Count, 1 To 4)
'Populate
I = 0
For Each V In colF
I = I + 1
With V
vRes(I, 1) = .Style
vRes(I, 2) = .Fabric
vRes(I, 3) = .Colour
vRes(I, 4) = .Size
End With
Next V
'Write the results
Set rRes = rRes.Resize(UBound(vRes, 1), UBound(vRes, 2))
With rRes
.Clear
.NumberFormat = "#"
.Value = vRes
.EntireColumn.AutoFit
End With
End Sub
Disregarding the previous regex/class method,
Option Explicit
Sub Fabrics_part_Deux()
Dim a As Long, b As Long
With Worksheets("Sheet1")
If .AutoFilterMode Then .AutoFilterMode = False
With .Range(.Cells(1, "A"), .Cells(.Rows.Count, "B").End(xlUp).Offset(0, 3))
With .Columns("B")
.Offset(1, 0).Replace what:=Chr(32), replacement:=vbNullString, lookat:=xlPart
End With
.AutoFilter field:=2, Criteria1:="<>"
.AutoFilter field:=3, Criteria1:=""
With .Resize(.Rows.Count - 1, 1).Offset(1, 1)
If CBool(Application.Subtotal(103, .Cells)) Then
With .SpecialCells(xlCellTypeVisible)
For a = 1 To .Areas.Count
With .Areas(a).Cells
.TextToColumns Destination:=.Cells(1), DataType:=xlFixedWidth, _
FieldInfo:=Array(Array(0, 1), Array(6, 1), Array(11, 1), Array(15, 2))
For b = 1 To .Rows.Count
.Cells(b, 2) = UCase$(.Cells(b, 2).Value2)
If CBool(InStr(1, .Cells(b, 4).Value2, Chr(47), vbBinaryCompare)) Then
.Cells(b, 4) = Trim(Split(.Cells(b, 4), Chr(47))(1))
End If
Next b
End With
Next a
End With
End If
End With
End With
If .AutoFilterMode Then .AutoFilterMode = False
End With
End Sub
In your code to output to the spreadsheet, you need to check for empty strings
I = 0
For Each V In colF
I = I + 1
With V
vRes(I, 1) = .Style
If len(.Fabric) > 0 then
vRes(I, 2) = .Fabric
vRes(I, 3) = .Colour
vRes(I, 4) = .Size
End If
End With
Next V

C++ to VB.NET Conversion: Assignment Within Expressions

Am converting some C++ code to VB.NET and need to convert assignments within expressions. Below are some C++ lines of code for which it's not clear what the converted results would be:
i2 = 1 + (i1 = i + i)
i4 = 1 + (i3 = n - i1)
wr = (wtemp = wr) * wpr - wi * wpi + wr
data(0) = (h1r = data(0)) + data(1)
data(0) = c1 * ((h1r = data(0)) + data(1))
Would the first line translate to:
If i2 = 1 Then i1 = i + i
?
Hans gave you the procedure - but just in case there's still any doubt about how to do this, your final result should be:
i1 = i + i
i2 = 1 + i1
i3 = n - i1
i4 = 1 + i3
wtemp = wr
wr = wtemp * wpr - wi * wpi + wr
h1r = data(0)
data(0) = h1r + data(1)
h1r = data(0)
data(0) = c1 * (h1r + data(1))
The code is already converted to VB.NET!
For example if you look at the following VB.NET code
Dim i2 As Int16
Dim i1 As Int16
Dim i As Int16
Dim data(0 To 1)
i = 1
i1 = 1
i2 = 0
i2 = 1 + (i1 = i + i) 'Same as your C++ code
MsgBox(i2)
It will return 1. The code translates to
i2 = 1 + (if i1= i+i)

Replace variables values between two files using VBS

I'm dealing with a script and I won't be able to create it without your help.
This is what I need: I have two .txt files, one contains variables (between two #) like these:
#PickupFolder#=E:/SonicDataFiles/AR_INT/GPP_VE/IN
#Db1Url#=jdbc:sonic:sqlserver://CARASETMS:1433;databaseName=CRM
The other .txt have variables that need to be completed from the previous file
#Db1Url#=
#Db1Pwd#=
I need to get every variable in the first file (I guess I have to use regular expression) and replace its value in the second file if the variable exits.
I would really appreciate if anyone has a similar script to get an idea. I'm trying to do it with VBS.
Thanks a lot.
Gerardo.
Buenos Aires, Argentina.
This was my original script:
'ReplaceScript "c:\Variables_INT.txt" "C:\AR_INT.tailoring.properties"
'DEFINE CONSTANTS
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
'DEFINE VARIABLES
strTxtFile = Wscript.Arguments(0)
strTailoringFile = Wscript.Arguments(1)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set WshShl = WScript.CreateObject("WScript.Shell")
Set objFileVariablesTXT = objFSO.OpenTextFile (strTxtFile, ForReading) 'Variables_INT.txt
Set objFileTailoring = objFSO.OpenTextFile (strTailoringFile, ForReading) 'AR_INT.tailoring.properties
Dim strQuartz, strPickupfFolder, strUrl, strDbPwd, strDbUser, strDbDestTable
strSearchString = objFileVariablesTXT.ReadAll
'SEARCH THE FILE FOR THE NEEDED DATA
vQuartz = InStr(strSearchString, "#QuartzJars#=")
vPickupFolder = InStr(strSearchString, "#PickupFolder#=")
vDbUrl = InStr(strSearchString, "#Db1Url#=")
vDbPwd = InStr(strSearchString, "#Db1Pwd#=")
vDbUser = InStr(strSearchString, "#Db1User#=")
vDbDestTable = InStr(strSearchString, "#DestinationTable#=")
'PARSE OUT THE NEEDED INFO
If vQuartz <> 0 Then
'vQuartz = vQuartz + 13
strQuartz = Mid(strSearchString, vQuartz, 304)
' WScript.Echo strQuartz
End If
If vPickupFolder <> 0 Then
'vPickupFolder = vPickupFolder + 15
strPickupfFolder = Mid(strSearchString, vPickupFolder, 50)
' WScript.Echo strPickupfFolder
End If
If vDbUrl <> 0 Then
'vDbUrl = vDbUrl + 9
strUrl = Mid(strSearchString, vDbUrl, 65)
' WScript.Echo strUrl
End If
If vDbPwd <> 0 Then
'vDbPwd = vDbPwd + 9
strDbPwd = Mid(strSearchString, vDbPwd, 17)
'WScript.Echo strDbPwd
End If
If vDbUser <> 0 Then
'vDbUser = vDbUser + 10
strDbUser = Mid(strSearchString, vDbUser, 25)
'WScript.Echo strDbUser
End If
If vDbDestTable <> 0 Then
'vDbDestTable = vDbDestTable + 19
strDbDestTable = Mid(strSearchString, vDbDestTable, 29)
'WScript.Echo strDbDestTable
End If
objFileVariablesTXT.Close
strReplaceString = objFileTailoring.ReadAll
arrReplacements = Array("#QuartzJars#=Ç" & strQuartz , "#PickupFolder#=Ç" & strPickupfFolder, "#Db1Url#=Ç" & strUrl, "#Db1Pwd#=Ç" & strDbPwd, "#Db1User#=Ç" &strDbUser, "#DestinationTable#=Ç" & strDbDestTable)
objFileTailoring.Close
Set objFileTailoring = Nothing
For Each strReplacement In arrReplacements
strReplaceWhat = Split(strReplacement, "Ç")(0)
'WScript.Echo strReplaceWhat
strReplaceWith = Split(strReplacement, "Ç")(1)
'WScript.Echo strReplaceWith
strReplaceString = Replace(strReplaceString, strReplaceWhat, strReplaceWith)
Next
'wScript.Echo strReplaceString
Set objFileTailoring = objFSO.OpenTextFile(strTailoringFile, 2, true)
objFileTailoring.Write strReplaceString
objFileTailoring.Close
Quick and Dirty:
Dim sFSpec1 : sFSpec1 = "..\data\frs.txt"
Dim sFSpec2 : sFSpec2 = "..\data\sec.txt"
Dim dicRpl : Set dicRpl = CreateObject( "Scripting.Dictionary" )
Dim reCut : Set reCut = New RegExp
reCut.Global = True
reCut.Pattern = "(#[^#]+#)\s*=\s*(.*?)\s*$"
Dim sAll : sAll = goFS.OpenTextFile( sFSpec1 ).ReadAll
WScript.Echo sAll
WScript.Echo "---------------"
Dim oMTS : Set oMTS = reCut.Execute( sAll )
Dim oMT
For Each oMT In oMTS
dicRpl( oMT.SubMatches( 0 ) ) = oMT.SubMatches( 1 )
Next
sAll = goFS.OpenTextFile( sFSpec2 ).ReadAll
WScript.Echo sAll
WScript.Echo "---------------"
Dim sKey
For Each sKey In dicRpl.Keys
sAll = Replace( sAll, sKey, dicRpl( sKey ) )
Next
WScript.Echo sAll
output:
#PickupFolder#=E:/SonicDataFiles/AR_INT/GPP_VE/IN
#Db1Url#=jdbc:sonic:sqlserver://CARASETMS:1433;databaseName=CRM
---------------
#Db1Url#=
#Db1Pwd#=
---------------
jdbc:sonic:sqlserver://CARASETMS:1433;databaseName=CRM=
#Db1Pwd#=
If that solves your problem in principle, we can nail down details.
ADDED:
As Jean-François Corbett surely is right, use the pattern
reCut.Pattern = "(#[^#]+#=)(.*?)\s*$"
and the final replacement
sAll = Replace( sAll, sKey, sKey & dicRpl( sKey ) )
This version assumes a strict #x#=[y] format in both files.
Tested this brute force approach, it works for me...
Dim FSO, txs, all, sourceLines, i, targetLines, j, delimiterPosition
Set FSO = CreateObject("Scripting.FileSystemObject")
set txs = FSO.OpenTextFile(".\source.txt", 1)
all=txs.ReadAll
txs.Close
sourceLines=Split(all,vbCrLf)
set txs = FSO.OpenTextFile(".\target.txt", 1)
all=txs.ReadAll
txs.Close
targetLines=Split(all,vbCrLf)
for i = 0 to ubound(sourceLines)
If sourceLines(i)<>"" Then
delimiterPosition = InStr(2, sourceLines(i), "#")
sourceVarName = Mid(sourceLines(i), 2, delimiterPosition - 2)
sourceVarValue = Mid(sourceLines(i), delimiterPosition + 2)
for j = 0 to ubound(targetLines)
If targetLines(j)<>"" Then
delimiterPosition = InStr(2, targetLines(j), "#")
targetVarName = Mid(targetLines(j), 2, delimiterPosition - 2)
If targetVarName = sourceVarName Then
targetLines(j) = targetLines(j) & sourceVarValue
End If
End If
next
End If
next
set txs = FSO.OpenTextFile(".\target.txt", 2)
for j = 0 to ubound(targetLines)
txs.WriteLine targetLines(j)
next
txs.Close
Target file is now:
#Db1Url#=jdbc:sonic:sqlserver://CARASETMS:1433;databaseName=CRM
#Db1Pwd#=

Problem with Win32_PhysicalMedia SerialNumber property

I wrote the following code to get the physical media serial number but in one of my computers it returns null instead.
Does anybody know what the problem is?
Thanks.
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
foreach( ManagementObject mo in searcher.Get() )
{
Console.WriteLine("Serial: {0}", mo["SerialNumber"]);
}
The Serial Number is optional, defined by the manufacturer, and for your device it is either blank or unsupported by the driver.
Virtually all hard drives have a serial number, but most USB-style Flash memory sticks do not (generally a cost issue). I would imagine most unbranded CD/DVD/BD discs would also be non-serialized.
Here is the code I used, the serial number somehow is returned raw with each pair of chars reversed (strange) and using Win32_PhysicalMedia gave different results if I ran the code as a user or an Administrator(more strange) - Windows 7 Ultimate, VS 2008 using VB only:
Function GetHDSerial() As String
Dim strHDSerial As String = String.Empty
Dim index As Integer = 0
Dim Data As String
Dim Data2 As String
Dim ndx As Integer
Dim query As New SelectQuery("Win32_DiskDrive")
Dim search As New ManagementObjectSearcher(query)
Dim info As ManagementObject
Try
For Each info In search.Get()
Data = info("SerialNumber")
Data2 = ""
For ndx = 1 To Data.Length - 1 Step 2
Data2 = Data2 & Chr(Val("&H" & Mid(Data, ndx, 2)))
Next ndx
Data = String.Empty
For ndx = 1 To Data2.Length - 1 Step 2
Data = Data & Mid(Data2, ndx + 1, 1) & Mid(Data2, ndx, 1)
Next
Data2 = Data
If Len(Data) < 8 Then Data2 = "00000000" 'some drives have no s/n
Data2 = Replace(Data2, " ", "") ' some drives pad spaces in the s/n
'forget removeable drives
If InStr(info("MediaType").ToString, "Fixed", CompareMethod.Text) > 0 Then
strHDSerial = strHDSerial & "Drive " & index.ToString & " SN: " & Data2 & vbCrLf
index += 1
End If
Next
Catch ex As Exception
strHDSerial = "Error retrieving SN for Drive "
msgbox(index.ToString)
End Try
Return strHDSerial
End Function