Can anyone convert this vb.net code to C#? - vb.net-to-c#

I'm facing troubles with converting this code ( for using this FFmpeg Wrapper ) to C# since it's the main language of my project .
I tried http://www.developerfusion.com/tools/convert/vb-to-csharp/
but the result code didn't work with me :(
I know it's a newbie request, I'm sorry ;
The Code :
Public WithEvents MediaConverter As New FFLib.Encoder
Private Sub ConOut(ByVal prog As String, ByVal tl As String) Handles MediaConverter.Progress
OperationPrgrss.Value = prog
Application.DoEvents()
End Sub
Private Sub stat(ByVal status) Handles MediaConverter.Status
StatusLbl.Text = status
Application.DoEvents()
End Sub

C# doesn't have a strict equivalent for the Handles keyword; what you need to do is add event handlers yourself in the constructor.
public Form1() {
...
// wire up events
MediaConverter.Progress += ConOut;
MediaConverter.Status += stat;
}
You don't need an equivalent for WithEvents, as that just tells VB there are events to be wired up, and in C# you do that yourself.
The rest is a very straightforward translation. A Sub is basically a function with void return type, ByVal and the Handles clauses can go away, keywords are lowercase, and the rest is just semicolons and braces.
For example,
private void ConOut(String prog, String tl) {
OperationPrgrss.Value = prog;
Application.DoEvents();
}

Related

Mocking Test : How-to refactor legacy singleton used in static

Well, I'm looking for the best way to refactor a (huge) legacy code-base and introducing some tests in it..There was no test framework. (yeah, I mean not at all)
It was an JEE 5 application. The goal is to revamp that in JEE7
Let me introduce a quick overview .
The end-users (those of them who are authorized) are free to evolve , configure many aspect of the application behavior by setting in the UI a bunch of preferences.
Theses are stored in an SQL table for the main part (the rest in some xml and properties files).
To fulfill this requirement, there is an #Startup object dedicated to build a sort-of huge map with all key-values.
Then all across the code base when a use case needs to adapt it's processing it checks the current value of the parameter(s) needed to its task.
A real case is that the app has to do a few operations on images;
For instance, Class ImgProcessing has to create thumbnail of a picture via this method :
Optional<Path> generateThumb_fromPath(Path origImg);
for this the method generateThumb_fromPath, calls Thumbnailer,
which uses a generic ImageProcessingHelper,
which holds a few set of generic image related tools and methods,
and specially an static method returning the wished dimensions of the thumbnail to be generated based on the original image constraints and some thumbnail preferences (keys = "THUMBNAIL_WIDTH" and "THUMBNAIL_HEIGHT").
These preferences are the user wishes for what size a thumbnail should have.
So far so good, nothing special.
Now the dark side of this :
The original JEE5 config loader is an bad old fashioned infamous singleton pattern as :
OldBadConfig {
private static OldBadConfig instance ;
public static getInstance(){
if(instance==null){
// create, initialize and populate our big preferences' map
}
return instance;
}
}
Then all across the whole code-base these preferences are used. In my refactoring effort I've already done using #Inject for injecting the singleton object.
But in static utilities ( no injection point available ) you have lots of this nasty calls :
OldBadConfig.getInstance.getPreference(key, defaultValue)
(Briefly I will explain that I use testNg + Mockito, I don't think the tools are relevant here, it seems to be more about an original terrible design,
but if I HAVE to change my toolbox (Junit or whatever) I will. But again I don't think the tooling is the root problem here. )
Trying to refactor the image part and make it test-friendly., I want to do this test with cut = instance of my Class Under Test:
#Test
public void firstTest(){
Optional<Path> op = cut.generateThumb_fromPath(targetPath);
// ..assertThatTheThumbnailWasCreated........
}
So in a few words ,
the execution flow will be like :
class under test --> some business implementation --> someutilities --> static_global_app_preference ---> other_class-othermethod.finalizingProcessing,
then return to the caller.
My testing effort halts here. How to mock the static_global_app_preference ?
How can I refactor the static_global_app_preference part from
*OldBadConfig.getInstance.getPreference(key, defaultValue)*
to something mockable where I could mock like :
Mockito.when(gloablConf.getPreference("THUMBNAIL_WIDTH", anyString)).thenReturn("32");
I've spent quite a time reading boks, blog posts etc all saying
'(these kind of) Singleton is EVIL'. You should NOT do that !
I think we all agree , thanks.
But what about a real word and effective solution to such really trivial, common tasks?
I can not add the singleton instance (or the preferences'map ) as parameters (because as it is already spread all across the code-base it will pollute all and every classes and methods . For instance in the exposed use case, it will pollute 5 methods in 4 classes just for one, poor, miserable, access to a parameter.
It's really not feasible.
So far I tried to refactor OldBadConfig class in two part : one with all initialization/write stuff,
and the other with only the read parts. that way I can at least make this a real JEE #Singleton and benefits from concurrent access once the startup is over and the configuration all loaded.
Then I tried to make this SharedGlobalConf accessible via a factory, called like :
SharedGlobalConf gloablConf= (new SharedGlobalConfFactory()).getShared();
then gloablConf.getPreference(key, defaultValue); is accessible.
It seems to be a little better than the original bottleneck, but didn't help at all for the testing part.
I thought the factory will ease everything but nothing like that comes out.
So there is my question :
For myself, I can split the OldBadConfig to an startup artefact doing the init and refesh, and to an SharedGlobalConf which is a JEE7 pure Singleton,
#Singleton
#ConcurrencyManagement(ConcurrencyManagementType.BEAN)
#Lock(LockType.READ)
Then, as for the legacy use case described here, How Can I make this reasonably mock-able ? Real word solutions are all welcomed.
Thanks sharing your wisdom and skills !
I will like to share my own answer.
Let's say we got these classes after the initial large OldBadConfig class was splitted :
#Startup AppConfigPopulator in charge of loading all information and populating the kind-of internal cache,
which is now a distinct SharedGlobalConf object. The populator is the only one in charge of feeding the SharedGlobalConf via :
#Override
public SharedGlobalConf sharedGlobalConf() {
if (sharedGlobalConf.isDirty()) {
this.refreshSharedGlobalConf();
}
return sharedGlobalConf;
}
private void refreshSharedGlobalConf() {
sharedGlobalConf.setParams(params);
sharedGlobalConf.setvAppTempPath_temp(getAppTempPath_temp());
}
In all components (by that I mean all Classes holding valid injection points) you just do your classic
#Inject private SharedGlobalConf globalConf;
For static utilities that can not do #Inject, we got an SharedGlobalConfFactory which handles the shared data to everything in a one-liner :
SharedGlobalConf gloablConf = (new SharedGlobalConfFactory()).getShared();
That way our old code base can be smoothly upgraded : #Inject in all valid components, And the (too many) old utilities that we can not reasonably rewrite them all in this refactoring step can get these
*OldBadConfig.getInstance.getPreference(key, defaultValue)*
,simply replaced by
(new SharedGlobalConfFactory()).getShared().getPreference(key, defaultValue);
And we are test-compliant and mockable !
Proof of concept :
A really critical Business demands is modeled in this class :
#Named
public class Usage {
static final Logger logger = LoggerFactory.getLogger(Usage.class);
#Inject
private SharedGlobalConf globalConf;#Inject
private BusinessCase bc;public String doSomething(String argument) {
logger.debug(" >>doSomething on {}", argument);
// do something using bc
Object importantBusinessDecision = bc.checks(argument);
logger.debug(" >>importantBusinessDecision :: {}", importantBusinessDecision);
if (globalConf.isParamFlagActive("StackOverflow_Required", "1")) {
logger.debug(" >>StackOverflow_Required :: TRUE");
// Do it !
return "Done_SO";
} else {
logger.debug(" >>StackOverflow_Required :: FALSE -> another");
// Do it another way
String resultStatus = importantBusinessDecision +"-"+ StaticHelper.anotherWay(importantBusinessDecision);
logger.debug(" >> resultStatus " + resultStatus);
return "Done_another_way " + resultStatus;
}
}
public void err() {
xx();
}
private void xx() {
throw new UnsupportedOperationException(" WTF !!!");
}
}
To get it's job done , we need a hand from our old companion StaticHelper :
class StaticHelper {
public static String anotherWay(Object importantBusinessDecision) {// System.out.println("zz #anotherWay on "+importantBusinessDecision);
SharedGlobalConf gloablConf = (new SharedGlobalConfFactory()).getShared();
String avar = gloablConf.getParamValue("deeperParam", "deeperValue");
//compute the importantBusinessDecision based on avar
return avar;
}
}
Usage of this =
#Named public class Usage {
static final Logger logger = LoggerFactory.getLogger(Usage.class);
#Inject
private SharedGlobalConf globalConf;
#Inject
private BusinessCase bc;
public String doSomething(String argument) {
logger.debug(" >>doSomething on {}", argument);
// do something using bc
Object importantBusinessDecision = bc.checks(argument);
logger.debug(" >>importantBusinessDecision :: {}", importantBusinessDecision);
if (globalConf.isParamFlagActive("StackOverflow_Required", "1")) {
logger.debug(" >>StackOverflow_Required :: TRUE");
// Do it !
return "Done_SO";
} else {
logger.debug(" >>StackOverflow_Required :: FALSE -> another");
// Do it another way
String resultStatus = importantBusinessDecision +"-"+ StaticHelper.anotherWay(importantBusinessDecision);
logger.debug(" >> resultStatus " + resultStatus);
return "Done_another_way " + resultStatus;
}
}
public void err() {
xx();
}
private void xx() {
throw new UnsupportedOperationException(" WTF !!!");
}}
As you see the old shared key/value holder is still used every where but this time, we can test
public class TestingAgainstOldBadStaticSingleton {
private final Boolean boolFlagParam;
private final String deepParam;
private final String decisionParam;
private final String argument;
private final String expected;
#Factory(dataProvider = "tdpOne")
public TestingAgainstOldBadStaticSingleton(String argument, Boolean boolFlagParam, String deepParam, String decisionParam, String expected) {
this.argument = argument;
this.boolFlagParam = boolFlagParam;
this.deepParam = deepParam;
this.decisionParam = decisionParam;
this.expected = expected;
}
#Mock
SharedGlobalConf gloablConf = (new SharedGlobalConfFactory()).getShared();
#Mock
BusinessCase bc = (new BusinessCase());
#InjectMocks
Usage cut = new Usage();
#Test
public void testDoSomething() {
String result = cut.doSomething(argument);
assertEquals(result, this.expected);
}
#BeforeMethod
public void setUpMethod() throws Exception {
MockitoAnnotations.initMocks(this);
Mockito.when(gloablConf.isParamFlagActive("StackOverflow_Required", "1")).thenReturn(this.boolFlagParam);
Mockito.when(gloablConf.getParamValue("deeperParam", "deeperValue")).thenReturn(this.deepParam);
SharedGlobalConfFactory.setGloablConf(gloablConf);
Mockito.when(bc.checks(ArgumentMatchers.anyString())).thenReturn(this.decisionParam);
}
#DataProvider(name = "tdpOne")
public static Object[][] testDatasProvider() {
return new Object[][]{
{"**AF-argument1**", false, "AF", "DEC1", "Done_another_way DEC1-AF"},
{"**AT-argument2**", true, "AT", "DEC2", "Done_SO"},
{"**BF-Argument3**", false, "BF", "DEC3", "Done_another_way DEC3-BF"},
{"**BT-Argument4**", true, "BT", "DEC4", "Done_SO"}};
}
The test is with TestNG and Mockito : it shows how we don't need to do the complex stuff (reading the sql table, the xml files etc..) but simply mock different set of values targeting just our sole business case. (if a nice fellow would accept to translate in other frameworks for those interested...)
As for the initial request was about the design allowing to reasonably refactor a -huge- existing code-base away from the 'static singleton anti-pattern' , while introducing tests and mocks I assume this a quite valid answer.
Will like to hear about your opinion and BETTER alternatives

Time left until Windows suspend

Is there a way to query windows how much time is left until it goes to suspend/sleep mode?
I am using vbscript and suspect there might be a WMI answer, but any language like c/c++, *.NET, or even java, if possible, may fit my needs.
EDIT
I want to be able to query Windows with a method, not to be alerted by events when it is about to suspend.
There's no API to know how much time is left since Windows will try to complete entering S3 (Sleep) or S4 (Hibernate) as quick as possible.
Windows will send a notification to all processes about the pending power state change and allow applications to prepare for that event.
You can find most of what you need here.
Basically you have 20 seconds to process the first message. Your process can delay replying to the message, taking care of all the various power cycle tasks, e.g. close files, save your state, etc.
You might want to call CallNtPowerInformation API function that takes the following params:
NTSTATUS WINAPI CallNtPowerInformation(
_In_ POWER_INFORMATION_LEVEL InformationLevel,
_In_ PVOID lpInputBuffer,
_In_ ULONG nInputBufferSize,
_Out_ PVOID lpOutputBuffer,
_In_ ULONG nOutputBufferSize
);
In the InformationLevel paramer you pass the SystemPowerInformation enum value that fills the lpOutputBuffer with a SYSTEM_POWER_INFORMATION structure:
typedef struct _SYSTEM_POWER_INFORMATION {
ULONG MaxIdlenessAllowed;
ULONG Idleness;
ULONG TimeRemaining;
UCHAR CoolingMode;
} SYSTEM_POWER_INFORMATION, *PSYSTEM_POWER_INFORMATION;
Then get the TimeRemaining, which is expressed in seconds.
edit: tested in VB.NET.
edit: code added.
Queryer.vb
Imports System.Runtime.InteropServices
Public Class Queryer
Const SystemPowerInformation As Integer = 12
Const STATUS_SUCCESS As Integer = 0
Private Structure SYSTEM_POWER_INFORMATION
Public MaxIdlenessAllowed As UInteger
Public Idleness As UInteger
Public TimeRemaining As Integer
Public CoolingMode As Byte
End Structure
<DllImport("PowrProf.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
Public Shared Function CallNtPowerInformation(
ByVal InformationLevel As Int32,
ByVal lpInputBuffer As IntPtr,
ByVal nInputBufferSize As UInt32,
ByVal lpOutputBuffer As IntPtr,
ByRef nOutputBufferSize As UInt32) As UInt32
End Function
Public Function Query() As Integer
Dim PowerInformation As SYSTEM_POWER_INFORMATION
Dim Status As IntPtr = IntPtr.Zero
Dim ReturnValue As UInteger
Try
Status = Marshal.AllocCoTaskMem(Marshal.SizeOf(GetType(SYSTEM_POWER_INFORMATION)))
ReturnValue = CallNtPowerInformation(SystemPowerInformation, Nothing, 0, Status, Marshal.SizeOf(GetType(SYSTEM_POWER_INFORMATION)))
PowerInformation = Marshal.PtrToStructure(Status, GetType(SYSTEM_POWER_INFORMATION))
Catch ex As Exception
Return 0
Finally
Marshal.FreeCoTaskMem(Status)
End Try
Return PowerInformation.TimeRemaining
End Function
End Class
Form:
Public Class Form1
Public Sub Loader() Handles Me.Load
Dim rolex As New Timer()
rolex.Interval = 500
AddHandler rolex.Tick, AddressOf TimerScattato
rolex.Start()
End Sub
Private Sub TimerScattato()
Dim secondi As Integer = q.Query()
Dim iSpan As TimeSpan = TimeSpan.FromSeconds(secondi)
lblTimeLeft.Text = String.Format("{0,2}:{1,2}:{2,2}", iSpan.Hours, iSpan.Minutes, iSpan.Seconds)
End Sub
Private q As New Queryer
End Class

import c++ structure to vb with dll

I'm having trouble with importing strings to VB from c++
I have my structure and export function declared like this in c++:
struct test
{
LPSTR text;
};
extern "C" __declspec(dllexport) test Func()
{
LPSTR text;
text = (LPSTR) "JUST TESTING";
test str;
str.text = text;
return str;
}
I'm importing this Func() function to VB I do "surprisingly" succeed with this text:
<DllImport("dlltest.dll", EntryPoint:="Func", CallingConvention:=CallingConvention.Cdecl)>
Private Shared Function AddFunction() As String
End Function
In this case, AddFunction() returns me the string I described in c++ ("JUST TESTING")
But when I try to define my structure in vb, I'm starting to get problems:
Public Structure test
Public t As String
End Structure
<DllImport("dlltest.dll", EntryPoint:="Func", CallingConvention:=CallingConvention.Cdecl)>
Private Shared Function AddFunction() As test
End Function
In this case, the program throws a Marshal Directive Exception error every time I
call the function AddFunction()
dim A as test
A = AddFunction()
I also tried writing this before defining my test structure
<System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)>
And this before defining Public t as string
_<System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)> _
And none of these help. I need to read my string from the structure. I have no problems reading integers the same way in structures. Only these strings. Do you have any ideas?

Program crashes when calling function from DLL when trying to copy an array

Today I tried to make my first DLL and my first application which would use a DLL.
The DLL is made in C++ and this is the code I'm calling:
void Graph::findPath_r(Node* pStart, Node* pEnd, std::vector<cell> &road, cell &costMx)
{
//.....
if(pEnd->getParent() != NULL)
{
while(!path.empty())
{
road.push_back(path.top()->getName());
costMx += path.top()->getGCost();
path.pop();
}
return;
}
return;
}
vector <int>tbcway;
int FUNCTION CalculatePath(int Start, int End, int * Array, int &cost)
{
dgraph->findPath_r(xNode[Start].NodeID ,xNode[End].NodeID,tbcway,cost);
dgraph->reset();
std::copy(tbcway.begin(), tbcway.end(), Array);
tbcway.clear();
return 1;
}
and this is how I declared it in VB.net and called it:
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("RCP.dll")> _
Public Shared Function LOAD_SYSTEM() As Boolean
End Function
<DllImport("RCP.dll")> _
Public Shared Function GetPluginVersion() As Integer
End Function
<DllImport("RCP.dll")> _
Public Shared Function CalculatePath(ByVal StartNode As Integer, ByVal EndNode As Integer, ByRef Array() As Array, ByRef cost As Integer) As Integer
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LOAD_SYSTEM()
MsgBox(GetPluginVersion().ToString())
Dim path(4096) As Array
Dim movecost As Integer
CalculatePath(1702, 27932, path, movecost)
End Sub
End Class
So, what is wrong with this code?
The error I am getting is:
A call to PInvoke function 'RCP GUI!RCP_GUI.Form1::CalculatePath' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
This is probably a calling convention mismatch.
Try decorating your DllImport with different calling conventions to see which works (my guess is that it should be cdecl).

What type should my variable be declared as?

I am new to C# / OOP and am working on converting an existing application into .net 4.0 framework.
My code is as follows:
Class abc
private IList<string[]> GetReportBatchList()
{
List<string[]> rowList = new List<string[]>();
SqlParameter[] prm = { new SqlParameter("#rpt_doc_type_id", SqlDbType.Int, 9) };
prm[0].Value = 101;
try
{
.....
.....
.....
}
return rowList;
}
class xyz
using abc;
Private Function GenerateReport()
Try
{
Dim rptBatchList As ??????
rptBatchList = GetReportBatchList()
While rptBatchList.Read()
......
......
......
}
catch
{
......
}
What type should rptBatchList be declared as?
Since the return value of GetReportBatchList() has IList of string as its type, it makes sense that rptBatchList should be the same type.
Your second example is VB, but you say you are using C#, so...
For C# it would be IList<string[]>.
My VB is a little rusty, but I think it would be IList(Of String()).
Hmmm... is this a question about correct return types, or a question about translating C# into VB.Net?
According to the function definition you have, rptBatchList will be of type IList<string[]> - obviously declared in the correct syntax for VB.Net.
Further to that, because it is a list of string arrays, it doesn't have a Read() function, so maybe you were looking for something that derives from DbDataReader instead (like a SqlDataReader)? If you do intend to stick with the current definition then you can use either a foreach or a for loop to iterate over the list elements, or you can use Linq extensions and use something like this:
rptBatchList.ForEach(z => { z.ForEach(x => doSomethingWithThisResultString(x)); } );
although that can get messy fast - you probably want to just stick with a couple of nested foreach loops.