Need help fixing Exception Unhandled - visual-studio

I am getting the following error:
System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string.
Parameter name: length'
(Look for Bold Italic on code *** that's where it is taking me to fix that)
Not sure what the problem is. Here is the whole code:
Imports GroceryApp.GroceryItem
Imports System.IO
Public Class GroceryItemForm
Private strFileName As String = String.Empty
Private Sub btnAddToBasket_Click(sender As Object, e As EventArgs) Handles btnAddToBasket.Click, AddToolStripMenuItem.Click
Dim gi As GroceryItem
Dim price As Double
' Validate that brand name is entered
If txtBrandName.Text = "" Then
MsgBox("Please input an Brand Name", , "Value Required")
txtBrandName.Focus()
Exit Sub
End If
' Validate that price is entered
If Not Double.TryParse(numPrice.Text, price) Then
MsgBox("Please input an Price", , "Value Required")
numPrice.Focus()
Exit Sub
End If
' Validate that Aisle is selected
If cboAisle.Text = "" Then
MsgBox("Please select an Aisle", , "Value Required")
cboAisle.Focus()
Exit Sub
End If
***txtScanNumber.Text = txtBrandName.Text.Substring(0, 3) & "1019"***
gi = New GroceryItem(txtScanNumber.Text, txtBrandName.Text, price)
gi.Type = [Enum].Parse(GetType(Aisle), cboAisle.Text)
gi.Description = txtDescription.Text
basket.Add(gi)
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit()
End Sub
Private Sub ViewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewToolStripMenuItem.Click
'Dim result As String = ""
'Dim i As Integer = 1
'For Each gi As GroceryItem In basket
'result = result & "Item " & i & vbNewLine & "Aisle: " & gi.Type.ToString & vbNewLine & "Scan Number: " & gi.ScanNumber & vbNewLine & "Brand Name: " & gi.BrandName & vbNewLine & vbNewLine
'i = i + 1
'Next
'MsgBox(result, , "Basket Details")
Dim oForm As BasketDisplayForm
oForm = New BasketDisplayForm()
oForm.Show()
oForm = Nothing
End Sub
Private Sub GroceryItemForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim oForm As LoginForm
oForm = New LoginForm()
oForm.Show()
oForm = Nothing
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Dim rowLine As String = ""
'If strFileName = String.Empty Then
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
strFileName = SaveFileDialog1.FileName
Dim fsStream As New FileStream(strFileName, FileMode.Append, FileAccess.Write)
Dim sw As New StreamWriter(fsStream)
Dim sb As New System.Text.StringBuilder
For Each Item As GroceryItem In basket
sb.AppendLine(String.Concat(Item.ScanNumber, ",", Item.Type.ToString, ",", Item.BrandName, ",", Item.Description, ",", Item.Price))
'rowLine = rowLine + Item.ScanNumber + "," + Item.Type.ToString + "," + Item.BrandName + "," + Item.Description + "," + Item.Price.ToString
Next
'IO.File.WriteAllText(strFileName, sb.ToString)
'rowLine = rowLine.Remove(rowLine.Length - 1, 1)
sw.WriteLine(sb)
sw.Flush()
MsgBox("Data Saved Successfully")
sw.Close()
basket.Clear()
End If
'End If
End Sub
Private Sub LoadToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LoadToolStripMenuItem.Click
Dim basketFile As StreamReader
Dim gi As GroceryItem
Dim sNo, brand, desc, aisle As String
Dim price As Double
Dim y As Integer
basket.Clear()
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
strFileName = OpenFileDialog1.FileName
basketFile = File.OpenText(strFileName)
' Read Power rating from file
Using sr As StreamReader = New StreamReader(strFileName)
Do While sr.Peek() > -1
For Each c As String In sr.ReadToEnd().Split(CType(Chr(10), Char))
sNo = ""
For Each d As String In c.Split(",")
If y = 0 Then
sNo = d
End If
If y = 1 Then
aisle = d
End If
If y = 2 Then
brand = d
End If
If y = 3 Then
desc = d
End If
If y = 4 Then
price = d
End If
y += 1
Next
If (sNo <> "") Then
gi = New GroceryItem(sNo, brand, price)
gi.Type = [Enum].Parse(GetType(Aisle), aisle)
gi.Description = desc
If (sNo <> "" & vbCr & "") Then
basket.Add(gi)
End If
End If
y = 0
Next
Loop
End Using
basketFile.Close()
End If
End Sub
End Class

Related

How can I convert varchar to numeric in visual studio?

Please help me,Im trying to do a fixed asset program in visual basic studio using sql server, Im stack in this.
I checked if my sql table data types match with the visual studio data types.
Public Class Equipos_de_Computacion
Dim sql As String = ""
Private Sub BtnInsertar_Click(sender As Object, e As EventArgs) Handles btnInsertar.Click
If (Me.txtCodigoInterno.Text = "") Then
MsgBox("El campo idententificacion no puede estar vacio", MsgBoxStyle.Critical, "Atencion")
Me.txtCodigoInterno.Select()
Else
Dim CodigoInterno As Integer
Dim NumerodeSerie As Integer
Dim NumerodeFactura As Integer
Dim FechadeCompra As Date
Dim Precio As Decimal
Dim Acargode As String = ""
Dim Estado As String = ""
Dim Depreciacion As Decimal
Dim Caracteristicas As String = ""
CodigoInterno = Me.txtCodigoInterno.Text
NumerodeSerie = Me.txtNumerodeSerie.Text
NumerodeFactura = Me.txtNumerodeFactura.Text
FechadeCompra = Me.DateTimePicker1.MinDate
Precio = CDec(txtPrecio.Text)
Acargode = Me.txtACargode.Text
Estado = Me.txtEstado.Text
Depreciacion = CDec(txtDepreciacion.Text)
Caracteristicas = Me.txtCaracteristicas.Text
cmd.CommandType = CommandType.Text
cmd.Connection = conn
sql = "INSERT INTO [Equipos de Computacion] (CodigoInterno, NumerodeSerie, NumerodeFactura, FechadeCompra, Precio, Acargode, Estado, Caracteristicas, Depreciacion) "
sql += "Values('" & CodigoInterno & "','" & NumerodeSerie & "','" & NumerodeFactura & "','" & FechadeCompra & "','" & CDec(Precio) & "','" & Acargode & "','" & Estado & "','" & Caracteristicas & "','" & CDec(Depreciacion) & ")"
MsgBox(sql)
cmd.CommandText = sql
Try
cmd.ExecuteNonQuery()
MsgBox("Registro insertado correctamente")
Catch ex As Exception
If ex.ToString.Contains("duplicate") Then
MsgBox("El registro ya existe en la base de datos")
Else
MsgBox(ex.ToString)
End If
End Try
End If
End Sub
it sends me converting varchar to numeric error.
Iam only able to insert integer numbers.With Cint
`Imports System.Data.SqlClient
Public Class Equipos_de_Computacion
Dim sql As String = ""
Private Sub BtnInsertar_Click(sender As Object, e As EventArgs) Handles btnInsertar.Click
If (Me.txtCodigoInterno.Text = "") Then
MsgBox("El campo idententificacion no puede estar vacio", MsgBoxStyle.Critical, "Atencion")
Me.txtCodigoInterno.Select()
Else
Dim CodigoInterno As Integer
Dim NumerodeSerie As Integer
Dim NumerodeFactura As Integer
Dim FechadeCompra As Date
Dim Precio As Decimal
Dim Acargode As String = ""
Dim Estado As String = ""
Dim Depreciacion As Decimal
Dim Caracteristicas As String = ""
CodigoInterno = CInt(Me.txtCodigoInterno.Text)
NumerodeSerie = CInt(Me.txtNumerodeSerie.Text)
NumerodeFactura = CInt(Me.txtNumerodeFactura.Text)
FechadeCompra = CDate(Me.DateTimePicker1.Text)
Precio = Me.nudPrecio.Value
Acargode = Me.txtACargode.Text
Estado = Me.txtEstado.Text
Depreciacion = Me.NudDepreciacion.Value
Caracteristicas = Me.txtCaracteristicas.Text
cmd.CommandType = CommandType.Text
cmd.Connection = conn
sql = "INSERT INTO [Equipos de Computacion] (CodigoInterno, NumerodeSerie, NumerodeFactura, FechadeCompra, Precio, Acargode, Estado, Caracteristicas, Depreciacion)"
sql += "Values( '" & CodigoInterno & "' , '" & NumerodeSerie & "' , '" & NumerodeFactura & "' ,'" & FechadeCompra & "', '" & Precio & "' ,'" & Acargode & "','" & Estado & "','" & Caracteristicas & "','" & Depreciacion & "' )"
MsgBox(sql)
cmd.CommandText = sql
Try
cmd.ExecuteNonQuery()
MsgBox("Registro insertado correctamente")
Catch ex As Exception
If ex.ToString.Contains("duplicate") Then
MsgBox("El registro ya existe en la base de datos")
Else
MsgBox(ex.ToString)
End If
End Try
End If
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvEquiposdeComputacion.CellContentClick
End Sub
Private Sub BtnMostrar_Click(sender As Object, e As EventArgs) Handles btnMostrar.Click
Dim DS As New DataSet
Dim DA As New SqlDataAdapter("Select * from [Equipos de Computacion]", conn)
DA.Fill(DS)
dgvEquiposdeComputacion.DataSource = DS.Tables(0)
End Sub
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
End Sub
Private Sub BtnTotalDepreciacion_Click(sender As Object, e As EventArgs) Handles btnTotalDepreciacion.Click
NudDepreciacion.Value = CDec(FormatNumber(nudPrecio.Value * 0.25, 2))
End Sub
Private Sub TxtPrecio_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub txtPrecio_KeyPress(sender As Object, e As KeyPressEventArgs) Handles nudPrecio.KeyPress
nudPrecio.DecimalPlaces = 2
End Sub
Private Sub txtPrecio_LostFocus(sender As Object, e As EventArgs)
Dim VarMonedaDolares As Double
VarMonedaDolares = nudPrecio.Value
nudPrecio.Value = CDec(FormatCurrency(VarMonedaDolares, 2))
End Sub
End Class`

Read WebSocket client data to the server vb.net

Good afternoon. I clarify that I don't know much about WebSockets, but I'm learning about it. I am trying to make a connection between vb.net (server) and browser (client) using WebSocket. Searching on the internet I could make this work (Websocket Server VB.NET - Data Frame) Currently I can send a message from vb.net to the browser, but I have not known how to read the messages that the client sends to the server .. I found a code about it, but I do not understand well how it could be implemented to my code (WebSocket Server, client -> server frame mask)
CLIENT
function connect(host) {
var ws = new WebSocket(host);
ws.onopen = function () {
console('connected');
//ws.send("test");
};
ws.onmessage = function (evt) {
console('reveived data:'+evt.data);
};
ws.onclose = function () {
console('socket closed');
};
SERVER
Imports System.Net.Sockets
Imports System.Threading
Imports System.Net
Public Class Form1
Dim serverTcp As TcpListener
Dim serverThread As Thread
Dim host_ As String = ""
Dim curSocket As Socket
Sub Main()
'' Start server
serverThread = New Thread(AddressOf serverProc)
serverThread.Start()
End Sub
Private Sub serverProc()
Try
'' Listen to port 5665
serverTcp = New TcpListener(System.Net.IPAddress.Parse(host_), 5665)
serverTcp.Start()
Console.WriteLine("Listen to port 5665 ...")
'' Accept any connection
While (True)
curSocket = serverTcp.AcceptSocket()
Dim thread As New Thread(AddressOf clientProc)
thread.Start(curSocket)
End While
Catch ex As Exception
End Try
End Sub
Private Sub clientProc(ByVal sck As Socket)
Try
Dim netStream As New NetworkStream(sck)
Dim netReader As New IO.StreamReader(netStream)
Dim netWriter As New IO.StreamWriter(netStream)
Dim key As String = ""
Console.WriteLine("Accept new connection ...")
'' Reading handshake message
While (True)
Dim line As String = netReader.ReadLine()
If line.Length = 0 Then
Exit While
End If
If (line.StartsWith("Sec-WebSocket-Key: ")) Then
key = line.Split(":")(1).Trim()
End If
Console.WriteLine("Data: " & line)
End While
'' Calculate accept-key
key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
key = getSHA1Hash(key)
'' Response handshake message
Dim response As String
response = "HTTP/1.1 101 Switching Protocols" & vbCrLf
response &= "Upgrade: websocket" & vbCrLf
response &= "Connection: Upgrade" & vbCrLf
response &= "Sec-WebSocket-Accept: " & key & vbCrLf & vbCrLf
netWriter.Write(response)
netWriter.Flush()
'' Sending message
SendMessage(sck, "SEND.. VB.NET")
Catch ex As Exception
End Try
End Sub
Sub Msg(t As String)
Console.WriteLine(t)
End Sub
Function getSHA1Hash(ByVal strToHash As String) As String
Dim sha1Obj As New System.Security.Cryptography.SHA1CryptoServiceProvider
Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash)
Dim result As String
bytesToHash = sha1Obj.ComputeHash(bytesToHash)
result = Convert.ToBase64String(bytesToHash)
Return result
End Function
Sub SendMessage(sck As Socket, message As String)
Dim rawData = System.Text.Encoding.UTF8.GetBytes(message)
Dim frameCount = 0
Dim frame(10) As Byte
frame(0) = CByte(129)
If rawData.Length <= 125 Then
frame(1) = CByte(rawData.Length)
frameCount = 2
ElseIf rawData.Length >= 126 AndAlso rawData.Length <= 65535 Then
frame(1) = CByte(126)
Dim len = CByte(rawData.Length)
frame(2) = CByte(((len >> 8) & CByte(255)))
frame(3) = CByte((len & CByte(255)))
frameCount = 4
Else
frame(1) = CByte(127)
Dim len = CByte(rawData.Length)
frame(2) = CByte(((len >> 56) & CByte(255)))
frame(3) = CByte(((len >> 48) & CByte(255)))
frame(4) = CByte(((len >> 40) & CByte(255)))
frame(5) = CByte(((len >> 32) & CByte(255)))
frame(6) = CByte(((len >> 24) & CByte(255)))
frame(7) = CByte(((len >> 16) & CByte(255)))
frame(8) = CByte(((len >> 8) & CByte(255)))
frame(9) = CByte((len & CByte(255)))
frameCount = 10
End If
Dim bLength = frameCount + rawData.Length
Console.WriteLine(frameCount)
Console.WriteLine(rawData.Length)
Dim reply(bLength + 1) As Byte
Dim bLim = 0
For i = 0 To frameCount - 1
Console.WriteLine(bLim)
reply(bLim) = frame(i)
bLim += 1
Next
For i = 0 To rawData.Length - 1
Console.WriteLine(bLim)
reply(bLim) = rawData(i)
bLim += 1
Next
sck.Send(reply)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
host_ = Dns.GetHostEntry(Dns.GetHostName()).AddressList _
.Where(Function(a As IPAddress) Not a.IsIPv6LinkLocal AndAlso Not a.IsIPv6Multicast AndAlso Not a.IsIPv6SiteLocal) _
.Last() _
.ToString()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Main()
End Sub
Private Sub btnEnviarMensaje_Click(sender As Object, e As EventArgs) Handles btnEnviarMensaje.Click
SendMessage(curSocket, txtMensaje.Text)
End Sub
End Class
it is simple if you want implement this in your vb.net project
you have to put this code anywhere in your project to calling
you also can use it as a "clientProc" private sub or you also
can insert this code in button1 object if you will click on button
after handshake it will give you return web browser websocket client message
Dim netStream As New NetworkStream(curSocket)
Dim bytesArray(1024) As [Byte]
Dim byteslen As Int32
byteslen = netStream.Read(bytesArray, 0, bytesArray.Length)
If bytesArray.Length > 1 Then
Msg("---------------------------------------------------")
Msg("data type: " & bytesArray(0))
Dim secondByte As Byte = bytesArray(1)
Dim theLength As UInteger = secondByte And 127
Dim indexFirstMask As Integer = 2
If theLength = 126 Then
indexFirstMask = 4
ElseIf theLength = 127 Then
indexFirstMask = 10
End If
Msg("indexFirstMask: " & indexFirstMask)
Dim masks As New List(Of Byte)
Dim x As Integer = indexFirstMask
While (x < indexFirstMask + 4)
masks.Add(bytesArray(x))
x += 1
End While
Dim indexFirstDataByte = indexFirstMask + 4
Dim decoded(byteslen - indexFirstDataByte) As Byte
Dim i As Integer = 0, j As Integer = 0
For i = indexFirstDataByte To byteslen Step 1
Dim mask As Byte = masks(j Mod 4)
Dim encodedByte As Byte = bytesArray(i)
decoded(j) = (encodedByte Xor mask)
j += 1
Next
Console.WriteLine("FROM CLIENT: '" & System.Text.Encoding.UTF8.GetString(decoded) & "'")
'Console.WriteLine("temp " + decoded.ToString)
SendMessage(curSocket, "CONNECTION_OK")
End If

My code throws an error that the connection associated with data reader is not closed

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Con = New MySqlConnection
Con.ConnectionString = "server = localhost; user = root; database= employee"
Try
Con.Open()
If TextBox1.Text = "" And TextBox2.Text = "" And TextBox3.Text = "" Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Add New Customer!")
Else
Dim theQuery As String = "SELECT * FROM accounts WHERE EmpNo=#EmpNo "
Dim cmd1 As MySqlCommand = New MySqlCommand(theQuery, Con)
cmd1.Parameters.AddWithValue("#EmpNo", TextBox1.Text)
Using reader As MySqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
reader.Close()
Else
' User does not exist, add them
Dim cmd As MySqlCommand = New MySqlCommand("Insert into [ordering].[dbo].[accounts] ([EmpNo],[Username],[password]) values ('" + TextBox1.Text + "','" + TextBox2.Text + "', '" + TextBox3.Text + "')", Con)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
End If
End Using
End If
Con.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
Con.Dispose()
End Try
End Sub

Excel VBA Copying Pic/Chart to another workbook

I currently have code written to take the fields of one workbook and copy into another workbook. I currently take a range and 'snapshot' it then save that as a separate .bmp file.
I also would like to take this snapshot and attach it into a cell of the workbook I'm copying everything over into. Anybody have any advice, or see here i can add code for this?
Sub Macro4()
'
' Record and File report
Dim Model As String
Dim IssueDate As String
Dim ConcernNo As String
Dim IssuedBy As String
Dim FollowedSEC As String
Dim FollowedBy As String
Dim RespSEC As String
Dim RespBy As String
Dim Timing As String
Dim Title As String
Dim PartNo As String
Dim Block As String
Dim Supplier As String
Dim Other As String
Dim Detail As String
Dim CounterTemp As String
Dim CounterPerm As String
Dim VehicleNo As String
Dim OperationNo As String
Dim Line As String
Dim Remarks As String
Dim ConcernMemosMaster As Workbook
Dim LogData As String
Dim newFile As String
Dim fName As String
Dim Filepath As String
Dim DTAddress As String
Dim pic_rng As Range
Dim ShTemp As Worksheet
Dim ChTemp As Chart
Dim PicTemp As Picture
'Determines if any required cells are empty and stops process if there are. displays error message.
If IsEmpty(Range("c2")) Or IsEmpty(Range("AT3")) Or IsEmpty(Range("BI2")) Or IsEmpty(Range("M7")) Or IsEmpty(Range("C10")) Or IsEmpty(Range("AP14")) Or IsEmpty(Range("C14")) Or IsEmpty(Range("C23")) Or IsEmpty(Range("C37")) Or IsEmpty(Range("J51")) Or IsEmpty(Range("AA51")) Or IsEmpty(Range("C55")) Or IsEmpty(Range("AR51")) Then
MsgBox "Please fill out all required fields and retry.", vbOKOnly
Exit Sub
End If
If Dir("N:\") = "" Then '"N" drive not found, abort sub
MsgBox "Error: Drive, path or file not found. Please email copy of file to: "
Exit Sub
End If
'assigns fields
Worksheets("ConcernMemo").Select
Model = Range("c2")
IssueDate = Range("AT3")
ConcernNo = Range("BC3")
IssuedBy = Range("BI2")
FollowedSEC = Range("BA9")
FollowedBy = Range("BD9")
RespSEC = Range("BG9")
RespBy = Range("BJ9")
Timing = Range("M7")
Title = Range("C10")
PartNo = Range("AP14")
Block = Range("AP16")
Supplier = Range("AP18")
Other = Range("AZ14")
Detail = Range("C14")
CounterTemp = Range("C23")
CounterPerm = Range("C37")
VehicleNo = Range("J51")
OperationNo = Range("AA51")
Remarks = Range("C55")
Line = Range("AR51")
LogData = Format(Now(), "mm_dd_yyyy_hh_mmAMPM")
fName = Range("BC3").Value
newFile = fName & "_" & Format(Now(), "mmddyyyy_hhmmAMPM")
Filepath = "N:\Newell K\Concern_Memo\Concern_Memo_File_Drop\Concern_Memo_Records\" & fName & "_" & Format(Now(), "mmddyyyy_hhmmAMPM")
DTAddress = CreateObject("WScript.Shell").SpecialFolders("Desktop") & Application.PathSeparator
'asks user is they are ready to send to database
If MsgBox("Are you ready to send record to database?", vbYesNo) = vbNo Then Exit Sub
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set pic_rng = Worksheets("ConcernMemo").Range("AK22:BK49")
Set ShTemp = Worksheets.Add
'Takes snapshot of image/sketch and saves to sharedrive
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:=ShTemp.Name
Set ChTemp = ActiveChart
pic_rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture
ChTemp.Paste
Set PicTemp = Selection
With ChTemp.Parent
.Width = PicTemp.Width + 8
.Height = PicTemp.Height + 8
End With
ChTemp.Export fileName:="N:\Newell K\Concern_Memo\Concern_Memo_File_Drop\Concern_Memo_Images\" & newFile & ".bmp", FilterName:="bmp"
ShTemp.Delete
'opens db file on sharedrive and copies fields over
Set ConcernMemosMaster = Workbooks.Open("N:\Newell K\Concern_Memo\concern_memos_DBMASTER.xlsx")
Worksheets("sheet1").Select
Worksheets("sheet1").Range("a1").Select
RowCount = Worksheets("sheet1").Range("a1").CurrentRegion.Rows.Count
With Worksheets("sheet1")
.Range("a1").Offset(RowCount, 0) = Model
.Range("b1").Offset(RowCount, 0) = IssueDate
.Range("c1").Offset(RowCount, 0) = ConcernNo
.Range("d1").Offset(RowCount, 0) = IssuedBy
.Range("e1").Offset(RowCount, 0) = FollowedSEC
.Range("f1").Offset(RowCount, 0) = FollowedBy
.Range("g1").Offset(RowCount, 0) = RespSEC
.Range("h1").Offset(RowCount, 0) = RespBy
.Range("i1").Offset(RowCount, 0) = Timing
.Range("j1").Offset(RowCount, 0) = Title
.Range("k1").Offset(RowCount, 0) = PartNo
.Range("l1").Offset(RowCount, 0) = Block
.Range("m1").Offset(RowCount, 0) = Supplier
.Range("n1").Offset(RowCount, 0) = Other
.Range("o1").Offset(RowCount, 0) = Detail
.Range("p1").Offset(RowCount, 0) = CounterTemp
.Range("q1").Offset(RowCount, 0) = CounterPerm
.Range("r1").Offset(RowCount, 0) = VehicleNo
.Range("s1").Offset(RowCount, 0) = OperationNo
.Range("t1").Offset(RowCount, 0) = Remarks
.Range("U1").Offset(RowCount, 0) = PicTemp
.Range("V1").Offset(RowCount, 0) = LogData
.Range("w1").Offset(RowCount, 0) = Filepath
.Range("x1").Offset(RowCount, 0) = Line
'saves a copy to of entire file to sharedrive
ThisWorkbook.SaveCopyAs fileName:="N:\Newell K\Concern_Memo\Concern_Memo_File_Drop\Concern_Memo_Records\" & newFile & ".xlsm"
'Saves copy to desktop
Application.DisplayAlerts = True
ThisWorkbook.SaveCopyAs DTAddress & newFile & ".xlsm"
MsgBox "A copy has been saved to your desktop"
ThisWorkbook.SendMail Recipients:="kaitlin.newell#nissan-usa.com", _
Subject:="New Concern Memo"
End With
ConcernMemosMaster.Save
ConcernMemosMaster.Close
Application.DisplayAlerts = True
MsgBox "Please close out file without saving"
End Sub
Try this out :
Range("A1:D4").CopyPicture Appearance:=xlScreen, Format:=xlBitmap
Range("A6").PasteSpecial
It will paste a copy of the "snapshot" of Range("A1:D4") at the cell A6.
EDIT : Since you have already set an object of that "target" workbook, you can use it to easily paste into it. Try this :
ConcernMemosMaster.Worksheets("sheet1").Range("A1:X1").CopyPicture Appearance:=xlScreen, Format:=xlBitmap
ConcernMemosMaster.Worksheets("sheet1").Range("B1").PasteSpecial

Need Visual Studio macro to add banner to all C# files

Can someone post a Visual Studio macro which goes through all C# source files in a project and adds a file banner? Extra credit if it works for any type of source file (.cs, .xaml, etc).
Here you go, I provide an example for .cs and .vb but shouldn't be hard for you to adjust it to your other file type needs: Edited to recursively add header to sub-folders
Sub IterateFiles()
Dim solution As Solution = DTE.Solution
For Each prj As Project In solution.Projects
IterateProjectFiles(prj.ProjectItems)
Next
End Sub
Private Sub IterateProjectFiles(ByVal prjItms As ProjectItems)
For Each file As ProjectItem In prjItms
If file.SubProject IsNot Nothing Then
AddHeaderToItem(file)
IterateProjectFiles(file.ProjectItems)
ElseIf file.ProjectItems IsNot Nothing AndAlso file.ProjectItems.Count > 0 Then
AddHeaderToItem(file)
IterateProjectFiles(file.ProjectItems)
Else
AddHeaderToItem(file)
End If
Next
End Sub
Private Sub AddHeaderToItem(ByVal file As ProjectItem)
DTE.ExecuteCommand("View.SolutionExplorer")
If file.Name.EndsWith(".cs") OrElse file.Name.EndsWith(".vb") Then
file.Open()
file.Document.Activate()
AddHeader()
file.Document.Save()
file.Document.Close()
End If
End Sub
Private Sub AddHeader()
Dim cmtHeader As String = "{0} First Line"
Dim cmtCopyright As String = "{0} Copyright 2008"
Dim cmtFooter As String = "{0} Footer Line"
Dim cmt As String
Select Case DTE.ActiveDocument.Language
Case "CSharp"
cmt = "//"
Case "Basic"
cmt = "'"
End Select
DTE.UndoContext.Open("Header Comment")
Dim ts As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)
ts.StartOfDocument()
ts.Text = String.Format(cmtHeader, cmt)
ts.NewLine()
ts.Text = String.Format(cmtCopyright, cmt)
ts.NewLine()
ts.Text = String.Format(cmtFooter, cmt)
ts.NewLine()
DTE.UndoContext.Close()
End Sub
Visual Studio macro to add file headers
Here is the jist of it. No, I have not debugged this, that is an excercise for the reader. And, this is done off the top of my head. (Except the File commenter...That's a real Macro that I use).
function CommentAllFiles
option explicit
Dim ActiveProjectFullName
Dim dte80 As EnvDTE80.Solution2
ActiveProjectFullName = dte80.Projects.Item(0).FullName
If ActiveProjectFullName = "" Then
MsgBox("No project loaded!")
Exit Sub
End If
Err.Number = 0
doc.Open(ActiveProjectFullName, "Text", True)
If Err.Number <> 0 Then
MsgBox("Open " + ActiveProjectFullName + " failed: " & Hex(Err.Number))
Exit Sub
End If
ActiveDocument.Goto(1, 1, vsMovementOptions.vsMovementOptionsMove)
' Build search string
Dim SearchString
Dim vsFindOptionsValue As Integer
SearchString = "^SOURCE=.*" + dn + "$"
while ActiveDocument.Selection.FindText(SearchString, vsFindOptions.vsFindOptionsFromStart + vsFindOptions.vsFindOptionsRegularExpression)
Dim TheFile
TheFile = ActiveDocument.Selection.Text
TheFile = Mid(TheFile, 8)
doc.Open(TheFile)
wend
ActiveDocument.Close()
end function
Tried and true "Flower Box" adder:
Function IsClassDef()
Dim ColNum
Dim LineNum
Dim sText
sText = ActiveDocument.Selection.ToString()
If sText = "" Then
'ActiveDocument.Selection.WordRight(dsExtend)
'sText = ActiveDocument.Selection
'sText = ucase(trim(sText))
End If
If (sText = "CLASS") Then
IsClassDef = True
Else
IsClassDef = False
End If
End Function
Sub AddCommentBlock()
'DESCRIPTION: Add Commecnt block to header, CPP files and Class Defs
AddCPPFileDesc()
End Sub
Sub AddCPPFileDesc()
'DESCRIPTION: Add File desc block to the top of a CPP file
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
Dim bOk, sExt, IsCpp, IsHdr, sHeader, IsCSharp
bOk = True
IsCpp = False
IsCSharp = False
If ActiveDocument.Selection.CurrentLine > 10 Then
If MsgBox("You are not at the top of the file. Are you sure you want to continue?", vbYesNo + vbDefaultButton2) = vbNo Then
bOk = False
End If
End If
If (bOk) Then
sExt = ucase(right(ActiveDocument.Name, 4))
IsCpp = sExt = ".CPP"
IsHdr = Right(sExt, 2) = ".H"
IsCSharp = sExt = ".CS"
If (IsCpp) Then
sHeader = left(ActiveDocument.Name, len(ActiveDocument.Name) - 3) + "h"
FileDescTopBlock(1)
editPoint.Insert("#include " + Chr(34) + "StdAfx.h" + Chr(34) + vbLf)
editPoint.Insert("#include " + Chr(34) + sHeader + Chr(34) + vbLf)
ElseIf (IsCSharp) Then
FileDescTopBlock(1)
Else
If IsHdr Then
'If IsCLassDef() Then
'AddClassDef()
'Else
AddHeaderFileDesc()
'End If
Else
FileDescTopBlock(1)
End If
End If
End If
End Sub
Sub AddHeaderFileDesc()
FileDescTopBlock(0)
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
editPoint.Insert("#pragma once" + vbLf)
End Sub
Sub FileDescTopBlock(ByVal HasRevHistory)
'DESCRIPTION: Add File desc block to the top of a CPP file
Dim selection As EnvDTE.TextSelection
ActiveDocument.Selection.StartOfLine()
ActiveDocument.Selection.EndOfLine()
Dim sComment
sComment = ActiveDocument.Selection.ToString()
If Left(sComment, 2) = "//" Then
ActiveDocument.Selection.Delete()
sComment = LTrim(Mid(sComment, 3))
Else
sComment = ""
End If
Dim sLineBreak
Dim sFileName
Dim sBlock
sLineBreak = "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////"
sFileName = ActiveDocument.Name
ActiveDocument.Selection.StartOfDocument()
sBlock = sLineBreak & vbLf & _
"// File : " & sFileName & vbLf & _
"// Author : Larry Frieson" & vbLf & _
"// Desc : " & sComment & vbLf & _
"// Date : " & CStr(Now.Date()) & vbLf & _
"//" & vbLf & _
"// Copyright © 20" + Right(CStr(Now.Year.ToString()), 2) + " MLinks Technologies. All rights reserved" + vbLf
If (HasRevHistory > 0) Then
sBlock = sBlock & _
"//" & vbLf & _
"// Revision History: " & vbLf & _
"// " & CStr(Now) & " created." & vbLf & _
"// " & vbLf
End If
sBlock = sBlock + sLineBreak + vbLf
Dim editPoint As EnvDTE.EditPoint
selection = DTE.ActiveDocument.Selection()
editPoint = selection.TopPoint.CreateEditPoint()
editPoint.Insert(sBlock)
End Sub
Hope this helps, or at least gives you some ideas. Again, I didn't test/debug the "source file looper", I figure you can handle that.
Larry

Resources