Dynamically updating dependent variables - javascript

Have just found a gaping hole in my cs knowledge... this code is written in VBA but I'd be really interested to know how to do this in javascript as well !
Basically I'm in a situation where a whole set of variables depends on one variable - something like this :
Sub test()
Dim start As Integer
Dim var1 As Integer
Dim var2 As Integer
Dim var3 As Integer
var1 = start + 1
var2 = start + 2
var3 = start + 3
End Sub
My problem is that I want the values of var1, var2 and var3 to update dynamically based on the value of start, for example
Sub test()
Dim start As Integer
Dim var1 As Integer
Dim var2 As Integer
Dim var3 As Integer
start = 0
var1 = start + 1
var2 = start + 2
var3 = start + 3
' would like to have var1 = 1, var2 = 2, var3 = 3
MsgBox "start = " & start & vbNewLine & _
"var1 = " & var1 & vbNewLine & _
"var2 = " & var2 & vbNewLine & _
"var3 = " & var3
start = 5
' would now like to have var1 = 6, var2 = 7, var3 = 8
MsgBox "start = " & start & vbNewLine & _
"var1 = " & var1 & vbNewLine & _
"var2 = " & var2 & vbNewLine & _
"var3 = " & var3
End Sub
But clearly this is not working, I get the same values
var1 = 1, var2 = 2, var3 = 3
both times. Is there a way to make this work in VBA ?
And is there a name for this kind of thing so I can better google it ? Something like "dynamic dependent variables" ? Many thanks !

I'm guessing that you are looking for something like Excel cell formulas and the way they cascade updates. There is no built-in mechanism for coding like that in VBA. There are some programming languages that use a paradigm called Functional Programming that behave in a similar way by chaining functions together and evaluating in a lazy manner, but VBA is more of a (weakly) object oriented, imperative flavor.
One way to solve this type of issue generally is by creating a class to encapsulate all your calculations and using member variables as the base elements of the calculations which would be set first, like start, and functions for the derivative numbers, like var1, var2, var3.
Here is an example. Create a class called clsRectangle and copy the following:
Option Compare Database
Option Explicit
Public length As Integer
Public width As Integer
Public Property Get diagonal() As Double
diagonal = VBA.Sqr((length ^ 2) + (width ^ 2))
End Property
Public Property Get area() As Integer
area = length * width
End Property
Public Property Get perimeter() As Integer
perimeter = 2 * (length + width)
End Property
Next create a module called mdlMain and add the following:
Public Sub Main()
Dim rect As clsRectangle
Set rect = New clsRectangle
With rect
.length = 3
.width = 5
MsgBox "perimeter: " & .perimeter & vbCrLf & _
"diagonal: " & .diagonal & vbCrLf & _
"area: " & .area & vbCrLf
'After changing the underlying numbers (like *start* in your example)
'area, perimeter and diagonal all return new values
.length = 2
.width = 7
MsgBox "perimeter: " & .perimeter & vbCrLf & _
"diagonal: " & .diagonal & vbCrLf & _
"area: " & .area & vbCrLf
End With
End Sub
Building a class at compile-time to handle formulaic calculations is good practice because it exposes your math and logic in a very maintainable way and benefits from the syntax and type-checking of the language. However, it does lack some of the flexibility of a run-time system. If you want to attempt something like that, I can give you some pointers, but it would be a pretty heavy lift to accomplish. I've done something similar in the past and had to implement [Topological Sort] to figure out what order to perform the calculation updates in based on a graph of prerequisites.
I can't speak to Javascript directly as I don't have too much experience with it. However, Javascript is a much more dynamic language than VBA and it's entirely possible that libraries already exist to do what you want.

as far as I'm aware this won't be possible in VBA. You could declare your variables at module level (outside of your procedure) and have them updating through a called function as outlined below. It's not quite as simple as you were perhaps expecting, but it is better than manually updating your variables every time 'start' changes.
Dim start As Integer
Dim var1 As Integer
Dim var2 As Integer
Dim var3 As Integer
Sub test()
start = 0
var1 = start + 1
var2 = start + 2
var3 = start + 3
' would like to have var1 = 1, var2 = 2, var3 = 3
MsgBox "start = " & start & vbNewLine & _
"var1 = " & var1 & vbNewLine & _
"var2 = " & var2 & vbNewLine & _
"var3 = " & var3
start = ChangeStart(5)
' would now like to have var1 = 6, var2 = 7, var3 = 8
MsgBox "start = " & start & vbNewLine & _
"var1 = " & var1 & vbNewLine & _
"var2 = " & var2 & vbNewLine & _
"var3 = " & var3
End Sub
Public Function ChangeStart(StartValue As Long)
start = StartValue
var1 = start + 1
var2 = start + 2
var3 = start + 3
End Function

Related

Different HMAC for CryptoJS and VB

I have to generate a HMACSHA256 in Visual Basic. Problem is, that I didnt receive the correct HMAC and get different HMACS
InputData = Test\nTest\n\nTest
secret = c39ff802b43a01c08ea759750c41d7d4bac6b1b884b3864d640b577cf1dca21a
HMACa = 330c55857e5ff197a407a9dcd41bbf03a2e8de0b351aba9a405139919b3cae57
HMACb = f701ea7028f20df11a52bee297a336de212655a8bad01d848eeaa87d0f76ee5e
JS(CryptoJS) -> HMACa (Tested directly)
PY -> HMACa (Tested directly)
JS(jsSHA) -> HMACb (Tested under: liavaag.org/English/SHA-Generator/HMAC/)
C#/VB -> HMACb (Tested directly)
Why do i get different HMAC's and what can i do to get HMACa in VB/C#??
Here is my VB Code:
Sub Main()
Dim sToHash As String = "Test\nTest\n\nTest"
Dim sKey As String = "c39ff802b43a01c08ea759750c41d7d4bac6b1b884b3864d640b577cf1dca21a"
Console.WriteLine(getHMAC(sToHash, sKey))
End Sub
Function getHMAC(ToHash As String, SecretKey As String) As String
Dim aoText() As Byte = System.Text.Encoding.UTF8.GetBytes(ToHash)
Dim aoKey() As Byte = System.Text.Encoding.UTF8.GetBytes(SecretKey)
Using oHmac As New System.Security.Cryptography.HMACSHA256(aoKey)
Dim sHash As Byte() = oHmac.ComputeHash(aoText)
Return ByteToString(sHash)
End Using
End Function
Function ByteToString(buff As Byte()) As String
Dim getbinary As String = ""
For i As Integer = 0 To buff.Length - 1
getbinary += buff(i).ToString("X2")
Next
Return (getbinary).ToLower
End Function
It's a lot easier than intended. VB/C# can't Encode '\n' as NewLine. In World of VisualBasic you have to write vbLf to Indicate a NewLine in a String
So the correct InputString is now:
"Test" + vbLf + "Test" + vbLf + vbLf + "Test"
Result => HMACa
Thanks anyway

Finding duplicates within strings

I have been handed a project at work where I need to find duplicate pairings from multiple rows within a dataset. While the data set is much larger, the main portion revolves around the date of a training, the location of a training, and the names of the trainers. So every row of data has a date, a location, and then a comma separated list of names:
Date Location Names
1/13/2014 Seattle A, B, D
1/16/2014 Dallas C, D, E
1/20/2014 New York A, D
1/23/2014 Dallas C, E
1/27/2014 Seattle B, D
1/30/2014 Houston C, A, F
2/3/2014 Washington DC D, A, F
2/6/2014 Phoenix B, E
2/10/2014 Seattle C, B
2/13/2014 Miami A, B, E
2/17/2014 Miami C, D
2/20/2014 New York B, E, F
2/24/2014 Houston A, B, F
My goal is to be able to find rows with similar pairings of names. One example would be to know that A & B were in paired in Seattle on 1/13, Miami on 2/13, and Houston on 2/24, even though the third name is different in each occurrence. So instead of just simply finding duplicates among the entire string of names, I would also like to find pairings among partial segments of the “Names” column.
Is this possible to do within Excel or would I need to use a programming language to accomplish the task?
While I can manually do this, it represents a lot of time that could be used towards other things. If there was a way that I could automate this it would make this portion of my task a lot simpler.
Thank you in advance for any assistance or advice on a way forward.
You can do it with VBA. The solution below assumes
Your data is on the active sheet in columns A:C
You results will be output in columns E:G
The output will be a list sorted by pairs, and then by dates, so you can easily see where pairs repeated.
The routine assumes no more than three trainers at a time, but could be modified add more possible combinations.
Cities with just a single trainer will be ignored.
The routine uses a Class module to gather the information, and two Collections to process the data. It also makes use of the feature that collections will not allow addition of two items with the same key.
Class Module
Rename the Class Module: cPairs
Option Explicit
Private pTrainer1 As String
Private pTrainer2 As String
Private pCity As String
Private pDT As Date
Public Property Get Trainer1() As String
Trainer1 = pTrainer1
End Property
Public Property Let Trainer1(Value As String)
pTrainer1 = Value
End Property
Public Property Get Trainer2() As String
Trainer2 = pTrainer2
End Property
Public Property Let Trainer2(Value As String)
pTrainer2 = Value
End Property
Public Property Get City() As String
City = pCity
End Property
Public Property Let City(Value As String)
pCity = Value
End Property
Public Property Get DT() As Date
DT = pDT
End Property
Public Property Let DT(Value As Date)
pDT = Value
End Property
Regular Module
Option Explicit
Option Compare Text
Public cP As cPairs, colP As Collection
Public colCityPairs As Collection
Public vSrc As Variant
Public vRes() As Variant
Public rRes As Range
Public I As Long, J As Long
Public V As Variant
Public sKey As String
Sub FindPairs()
vSrc = Range("A1", Cells(Rows.Count, "C").End(xlUp))
Set colP = New Collection
Set colCityPairs = New Collection
'Collect Pairs
For I = 2 To UBound(vSrc)
V = Split(Replace(vSrc(I, 3), " ", ""), ",")
If UBound(V) >= 1 Then
'sort the pairs
SingleBubbleSort V
Select Case UBound(V)
Case 1
AddPairs V(0), V(1)
Case 2
AddPairs V(0), V(1)
AddPairs V(0), V(2)
AddPairs V(1), V(2)
End Select
End If
Next I
ReDim vRes(0 To colCityPairs.Count, 1 To 3)
vRes(0, 1) = "Date"
vRes(0, 2) = "Location"
vRes(0, 3) = "Pairs"
For I = 1 To colCityPairs.Count
With colCityPairs(I)
vRes(I, 1) = .DT
vRes(I, 2) = .City
vRes(I, 3) = .Trainer1 & ", " & .Trainer2
End With
Next I
Set rRes = Range("E1").Resize(UBound(vRes, 1) + 1, UBound(vRes, 2))
With rRes
.EntireColumn.Clear
.Value = vRes
With .Rows(1)
.HorizontalAlignment = xlCenter
.Font.Bold = True
End With
.Sort key1:=.Columns(3), order1:=xlAscending, key2:=.Columns(1), order2:=xlAscending, _
Header:=xlYes
.EntireColumn.AutoFit
V = VBA.Array(vbYellow, vbGreen)
J = 0
For I = 2 To rRes.Rows.Count
If rRes(I, 3) = rRes(I - 1, 3) Then
.Rows(I).Interior.Color = .Rows(I - 1).Interior.Color
Else
J = J + 1
.Rows(I).Interior.Color = V(J Mod 2)
End If
Next I
End With
End Sub
Sub AddPairs(T1, T2)
Set cP = New cPairs
With cP
.Trainer1 = T1
.Trainer2 = T2
.City = vSrc(I, 2)
.DT = vSrc(I, 1)
sKey = .Trainer1 & "|" & .Trainer2
On Error Resume Next
colP.Add cP, sKey
If Err.Number = 457 Then
Err.Clear
colCityPairs.Add colP(sKey), sKey & "|" & colP(sKey).DT & "|" & colP(sKey).City
colCityPairs.Add cP, sKey & "|" & .DT & "|" & .City
Else
If Err.Number <> 0 Then Stop
End If
On Error GoTo 0
End With
End Sub
Sub SingleBubbleSort(TempArray As Variant)
'copied directly from support.microsoft.com
Dim Temp As Variant
Dim I As Integer
Dim NoExchanges As Integer
' Loop until no more "exchanges" are made.
Do
NoExchanges = True
' Loop through each element in the array.
For I = LBound(TempArray) To UBound(TempArray) - 1
' If the element is greater than the element
' following it, exchange the two elements.
If TempArray(I) > TempArray(I + 1) Then
NoExchanges = False
Temp = TempArray(I)
TempArray(I) = TempArray(I + 1)
TempArray(I + 1) = Temp
End If
Next I
Loop While Not (NoExchanges)
End Sub
Ok. I got bored and did this whole thing in Python code. I assume you are familiar with the language; however, you should be able to get the following piece of code to work on any computer with Python installed.
I have made a few assumptions. For instance, I have used your example input as definite input.
A few things which will mess up the program:
Not entering with case sensitivity. Beware of capital letters etc.
Having a inputfile which has the following row: "Date Location Names". Just remove and keep straight facts in the file. I got lazy and do not bother adjusting this.
A ton of other small stuff. Just do what the program asks you to do and dont enter funky input.
About program:
Revolves around using a dictionary with person names as keys. The values in the dictionary is a set with tuples containing the places they've been during what date. By then comparing these sets and getting the intersection, we can find the answer.
Kinda messy since I took this as Python practice. Have not coded in Python for a while and I got a thrill out of doing it all without utilizing objects. Just follow the "instructions" and keep the inputfile, which stores all information, in the same folder as the piece of code are running.
As a side note, you might want to check that the program yields correct output.
If you have any questions, feel free to contact me.
def readWord(line, stringIndex):
word = ""
while(line[stringIndex] != " "):
word += line[stringIndex]
stringIndex += 1
return word, stringIndex
def removeSpacing(line, stringIndex):
while(line[stringIndex] == " "):
stringIndex += 1
return stringIndex
def readPeople(line, stringIndex):
lineSize = len(line)
people = []
while(stringIndex < lineSize):
people.append(line[stringIndex])
stringIndex += 3
return people
def readLine(travels, line):
stringIndex = 0
date, stringIndex = readWord(line, stringIndex)
stringIndex = removeSpacing(line, stringIndex)
location, stringIndex = readWord(line, stringIndex)
stringIndex = removeSpacing(line, stringIndex)
people = readPeople(line, stringIndex)
for person in people:
if(person not in travels.keys()):
travels[person] = set()
travels[person].add((date, location))
return travels
def main():
f = open(input("Enter filename (must be in same folder as this program code. For instance, name could be: testDocument.txt\n\n"))
travels = dict()
for line in f:
travels = readLine(travels, line)
print("\n\n\n\n PROGRAM RUNNING \n \n")
while(True):
persons = []
userInput = "empty"
while(userInput):
userInput = input("Enter person name (Type Enter to finish typing names): ")
if(userInput):
persons.append(userInput)
output = travels[persons[0]]
for person in persons[1:]:
output = output.intersection(travels[person])
print("")
for hit in output:
print(hit)
print("\nFINISHED WITH ONE RUN. STARTING NEW ONE\n")

Format SQL Query Result into web menu

I am trying to bhuild a drill down menu for my website, where user will click on a category and it will show the subcategories of that clicked category, there could be n-levels.
I am able to write sql query which returns the output exactaly as I want, but the problem is...I dont want to show the whole menu to end user, I would like to open/expand only clicked category.
my Query output is:
1 IPTV
2 Jadoo Tv
3 Shava Tv
4 Jalva Tv
5 Programming
6 Microsoft
7 Asp.Net
8 PHP
so by default IPTV & Programming Should be displayed, since they are parent, and when I click on IPTV it should open the children of IPTV, like I said there could be n-levels.
I was thinking, I can load the output of query to webpage and then control the menu navigation with css/javascript.
do you guys have any ideas?
ok, here is the complete code for markup (after I get the result from sql sp).
Private Sub CreateLeftMenu()
Dim dt As DataTable = DAL.ReturnMSSQLData("EXEc CategoryTree")
Dim str As New StringBuilder
Dim catname As String = ""
Dim catid As Integer = 0
Dim parent As Integer = 0
Dim sort As String = ""
Dim keys As Array
Dim display As String = "none"
For Each item As DataRow In dt.Rows
catname = Replace(item("CatName"), " ", " ")
catid = item("id")
parent = item("parent")
sort = item("sort")
If parent = 0 Then
str.Append("<div class='group_" & parent & "'><a href='/pages/index.aspx?cat=" & sort & "' id='group_" & catid & "'>" & catname & "</a></div>")
Else
If Len(Me.GroupID) > 0 Then
keys = Split(Me.GroupID, "_")
For Each item1 As String In keys
If CInt(item1) = parent Then
str.Append("<div class='group_" & parent & "' style='display:block'><a style='text-decoration:none' href='/pages/index.aspx?cat=" & sort & "' id='group_" & catid & "'>" & catname & "</a></div>")
Else
'str.Append("<div class='group_" & parent & "' style='display:none'><a style='text-decoration:none' href='/pages/index.aspx?cat=" & sort & "' id='group_" & catid & "'>" & catname & "</a></div>")
End If
Next
End If
End If
Next
LMenu.Text = str.ToString
End Sub

Requesting field names and values from form and add them on the fly in a script

Hi I have a form and the action is submitting into a script named autoform.asp. In this script I usually request the fields values like this: txtFirstName = Request.Form("txtFirstname")
Now I want to make this to work dynamically without hard coding the requests in the script where the form is posting.
I managed to do this code to get the the form fields dynamically but they are not being loaded on the fly.
For Each Item In Request.Form
fieldName = Item
fieldValue = Request.Form(Item)
Response.Write(""& fieldName &" = Request.Form("""& fieldName &""")")
Next
The Response.Write is not good because it is stopping my script to continue. That said the values showing are correct. Can someone help me please? Maybe I need an array? and If yes how I can continue this process? THANKS
EDIT as per comment below
You can use the Execute statement to mimic import_request_variables from php
For Each Item In Request.Form
ItemValue = Request.Form(Item)
Execute Item & " = """ & ItemValue & """"
Next
If you are intending to output
Firstname = Request.Form("Firstname")
then use
<%
For Each Item In Request.Form
fieldName = Item
fieldValue = Request.Form(Item)
Response.Write(fieldName & " = Request.Form(""" & fieldName & """)")
Next
%>
If you are intending to output
Firstname = "John"
then use
<%
For Each Item In Request.Form
fieldName = Item
fieldValue = Request.Form(Item)
Response.Write(fieldName & " = """ & fieldValue & """")
Next
%>
I think you might be able to work something out using Execute(), eg
<%# language = "VBScript" CodePage = 65001 %>
<%
option explicit
dim q
for each q in Request.QueryString
dim s
s = "dim " & q & vbCrLf & _
q & " = """ & Request.QueryString(q) & """" & vbCrLf & _
"Response.Write ""Value of " & q & " is "" & " & q & vbCrLf
%>
<pre><%= s %></pre>
<hr/>
<%
Execute s
%><hr/><%
next
%>
(I've used the querystring collection so it's easier to test). So input like
http://.../test-asp.asp?p=1&c=328904
will generate something like
dim p
p = "1"
Response.Write "Value of p is " & p
Value of p is 1
dim c
c = "328904"
Response.Write "Value of c is " & c
Value of c is 328904
it depends on what you actually need to do.

how to implement regions/code collapse in javascript

How can you implement regions a.k.a. code collapse for JavaScript in Visual Studio?
If there are hundreds of lines in javascript, it'll be more understandable using code folding with regions as in vb/C#.
#region My Code
#endregion
Good news for developers who is working with latest version of visual studio
The Web Essentials are coming with this feature .
Check this out
Note: For VS 2017 use JavaScript Regions : https://marketplace.visualstudio.com/items?itemName=MadsKristensen.JavaScriptRegions
Microsoft now has an extension for VS 2010 that provides this functionality:
JScript Editor Extensions
Thats easy!
Mark the section you want to collapse and,
Ctrl+M+H
And to expand use '+' mark on its left.
For those about to use the visual studio 2012, exists the Web Essentials 2012
For those about to use the visual studio 2015, exists the Web Essentials 2015.3
The usage is exactly like #prasad asked
Blog entry here explains it and this MSDN question.
You have to use Visual Studio 2003/2005/2008 Macros.
Copy + Paste from Blog entry for fidelity sake:
Open Macro Explorer
Create a New Macro
Name it OutlineRegions
Click Edit macro and paste the following VB code:
Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.Collections
Public Module JsMacros
Sub OutlineRegions()
Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Const REGION_START As String = "//#region"
Const REGION_END As String = "//#endregion"
selection.SelectAll()
Dim text As String = selection.Text
selection.StartOfDocument(True)
Dim startIndex As Integer
Dim endIndex As Integer
Dim lastIndex As Integer = 0
Dim startRegions As Stack = New Stack()
Do
startIndex = text.IndexOf(REGION_START, lastIndex)
endIndex = text.IndexOf(REGION_END, lastIndex)
If startIndex = -1 AndAlso endIndex = -1 Then
Exit Do
End If
If startIndex <> -1 AndAlso startIndex < endIndex Then
startRegions.Push(startIndex)
lastIndex = startIndex + 1
Else
' Outline region ...
selection.MoveToLineAndOffset(CalcLineNumber(text, CInt(startRegions.Pop())), 1)
selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
selection.OutlineSection()
lastIndex = endIndex + 1
End If
Loop
selection.StartOfDocument()
End Sub
Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer)
Dim lineNumber As Integer = 1
Dim i As Integer = 0
While i < index
If text.Chars(i) = vbCr Then
lineNumber += 1
i += 1
End If
i += 1
End While
Return lineNumber
End Function
End Module
Save the Macro and Close the Editor
Now let's assign shortcut to the macro. Go to Tools->Options->Environment->Keyboard and search for your macro in "show commands containing" textbox
now in textbox under the "Press shortcut keys" you can enter the desired shortcut. I use Ctrl+M+E. I don't know why - I just entered it first time and use it now :)
By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable.
The JSEnhancements plugin for Visual Studio addresses this nicely.
For those who have come here for Visual Studio Code, the same syntax works
// #region MongoDB Client
const MongoClient = require('mongodb').MongoClient;
const url = constants.credentials["uat"].mongo.url
MongoClient.connect(url, { useUnifiedTopology: true }, function (err, client) {
if (err) {
console.log(err);
}
else {
docDB = client.db("middlewareDB");
}
});
// #endregion
When collapsed, it looks like below
Thanks to 0A0D for a great answer. I've had good luck with it. Darin Dimitrov also makes a good argument about limiting the complexity of your JS files. Still, I do find occasions where collapsing functions to their definitions makes browsing through a file much easier.
Regarding #region in general, this SO Question covers it quite well.
I have made a few modifications to the Macro to support more advanced code collapse. This method allows you to put a description after the //#region keyword ala C# and shows it in the code as shown:
Example code:
//#region InputHandler
var InputHandler = {
inputMode: 'simple', //simple or advanced
//#region filterKeys
filterKeys: function(e) {
var doSomething = true;
if (doSomething) {
alert('something');
}
},
//#endregion filterKeys
//#region handleInput
handleInput: function(input, specialKeys) {
//blah blah blah
}
//#endregion handleInput
};
//#endregion InputHandler
Updated Macro:
Option Explicit On
Option Strict On
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Imports System.Collections.Generic
Public Module JsMacros
Sub OutlineRegions()
Dim selection As EnvDTE.TextSelection = CType(DTE.ActiveDocument.Selection, EnvDTE.TextSelection)
Const REGION_START As String = "//#region"
Const REGION_END As String = "//#endregion"
selection.SelectAll()
Dim text As String = selection.Text
selection.StartOfDocument(True)
Dim startIndex As Integer
Dim endIndex As Integer
Dim lastIndex As Integer = 0
Dim startRegions As New Stack(Of Integer)
Do
startIndex = text.IndexOf(REGION_START, lastIndex)
endIndex = text.IndexOf(REGION_END, lastIndex)
If startIndex = -1 AndAlso endIndex = -1 Then
Exit Do
End If
If startIndex <> -1 AndAlso startIndex < endIndex Then
startRegions.Push(startIndex)
lastIndex = startIndex + 1
Else
' Outline region ...
Dim tempStartIndex As Integer = CInt(startRegions.Pop())
selection.MoveToLineAndOffset(CalcLineNumber(text, tempStartIndex), CalcLineOffset(text, tempStartIndex))
selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
selection.OutlineSection()
lastIndex = endIndex + 1
End If
Loop
selection.StartOfDocument()
End Sub
Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer) As Integer
Dim lineNumber As Integer = 1
Dim i As Integer = 0
While i < index
If text.Chars(i) = vbLf Then
lineNumber += 1
i += 1
End If
If text.Chars(i) = vbCr Then
lineNumber += 1
i += 1
If text.Chars(i) = vbLf Then
i += 1 'Swallow the next vbLf
End If
End If
i += 1
End While
Return lineNumber
End Function
Private Function CalcLineOffset(ByVal text As String, ByVal index As Integer) As Integer
Dim offset As Integer = 1
Dim i As Integer = index - 1
'Count backwards from //#region to the previous line counting the white spaces
Dim whiteSpaces = 1
While i >= 0
Dim chr As Char = text.Chars(i)
If chr = vbCr Or chr = vbLf Then
whiteSpaces = offset
Exit While
End If
i -= 1
offset += 1
End While
'Count forwards from //#region to the end of the region line
i = index
offset = 0
Do
Dim chr As Char = text.Chars(i)
If chr = vbCr Or chr = vbLf Then
Return whiteSpaces + offset
End If
offset += 1
i += 1
Loop
Return whiteSpaces
End Function
End Module
This is now natively in VS2017:
//#region fold this up
//#endregion
Whitespace between the // and # does not matter.
I do not know what version this was added in, as I cannot find any mention of it in the changelogs. I am able to use it in v15.7.3.
For VS 2019, this should work without installing anything:
//#region MyRegion1
foo() {
}
//#endregion
//#region MyRegion2
bar() {
}
//#endregion
It works like a charm in PhpStorm
//#region My Region 1
...
//#endregion
//#region My Region 2
...
//#endregion
On VS 2012 and VS 2015 install WebEssentials plugin and you will able to do so.
http://vswebessentials.com/features/javascript
For visual studio 2017.
//#region Get Deactivation JS
.
.
//#endregion Get Deactivation JS
This was not working earlier so I downloaded extension from here
Extension Name(JavaScript Regions) By Mads Kristensen
if you are using Resharper
fallow the steps in this pic
then write this in template editor
//#region $name$
$END$$SELECTION$
//#endregion $name$
and name it #region as in this picture
hope this help you
None of these answers did not work for me with visual studio 2017.
The best plugin for VS 2017: JavaScript Regions
Example 1:
Example 2:
Tested and approved:
Region should work without changing settings
//#region Optional Naming
var x = 5 -0; // Code runs inside #REGION
/* Unnecessary code must be commented out */
//#endregion
To enable collapsing comment area /**/
/* Collapse this
*/
Settings -> Search "folding" -> Editor: Folding Strategy -> From "auto" to "indentation".
TAGS: Node.js Nodejs Node js
Javascript ES5 ECMAScript comment folding hiding region
Visual studio code vscode 2018 version 1.2+
https://code.visualstudio.com/updates/v1_17#_folding-regions
Not only for VS but nearly for all editors.
(function /* RegionName */ () { ... })();
Warning: has disadvantages such as scope.

Categories

Resources