|
I can't claim to deeply understand these two posts, but their "depth," and the fascinating responses, get my up-votes
If you have time/inclination to say something about the context in this scenario that leads you to need to compose executable code, and modify objects, that would be very interesting.
thanks, Bill
«Tell me and I forget. Teach me and I remember. Involve me and I learn.» Benjamin Franklin
|
|
|
|
|
|
I'm following this example[^]
Here's my code:
using System.Collections.Generic;
using EnvDTE;
namespace MyApp
{
public class IISDebugAttach
{
public void AttachToIIS()
{
bool attached = false;
List<string> listProcess = new List<string>();
listProcess.Add("aspnet_wp.exe");
listProcess.Add("w3wp.exe");
listProcess.Add("webdev.webserver.exe");
foreach (Process process in DTE.Debugger.LocalProcesses)
{
foreach (var processName in listProcess)
{
if (process.Name.ToLower().IndexOf(processName) != -1)
{
process.Attach();
}
}
}
}
}
}
I get a compilation error on the first FOREACh saying "An object reference is required for the non-static field, method, or property '_DTE.Debugger'"
What am I doing wrong here???
If it's not broken, fix it until it is
|
|
|
|
|
DTE is a class, but Debugger is not a static property - you want the instance that is passed in as the method parameter in the example:
public static void LocalProcesses(DTE dte)
{
...
EnvDTE.Processes processes = dte.Debugger.LocalProcesses;
I've not tried any of this - never had the need - but does this help: HOWTO: Get an EnvDTE.DTE instance from a Visual Studio package[^]
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
OriginalGriff wrote: you want the instance that is passed in as the method parameter in the example:
What parameter? What example are you referring to? The example I quoted has no param being passed in. Where do you see ...void LocalProcesses(DTE dte)?
If it's not broken, fix it until it is
|
|
|
|
|
Kevin Marois wrote: What parameter? What example are you referring to?
The example you linked to...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
I think I figured it out. I needed:
DTE dte = (DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.14.0");
If it's not broken, fix it until it is
|
|
|
|
|
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Thanks man
If it's not broken, fix it until it is
|
|
|
|
|
You're welcome!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
 Works great! Here's the entire class. I'm going to add to it to accept a list of processes to attach, then make it a VS addin that I can launch from a toolbar.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using EnvDTE;
namespace MyApp
{
public static class IISDebugAttach
{
public static void AttachToIIS()
{
MessageFilter.Register();
DTE dte = (DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.14.0");
var listProcess = new List<string>();
listProcess.Add("iisexpress");
var processes = dte.Debugger.LocalProcesses;
try
{
foreach (Process process in processes)
{
foreach (var processName in listProcess)
{
if (!string.IsNullOrEmpty(process.Name))
{
string procName = process.Name;
if (procName.ToLower().IndexOf(processName, StringComparison.Ordinal) != -1)
{
process.Attach();
}
}
}
}
}
catch (Exception e)
{
int x = 1;
}
MessageFilter.Revoke();
}
public class MessageFilter : IOleMessageFilter
{
public static void Register()
{
IOleMessageFilter newFilter = new MessageFilter();
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(newFilter, out oldFilter);
}
public static void Revoke()
{
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(null, out oldFilter);
}
int IOleMessageFilter.HandleInComingCall(int dwCallType,
System.IntPtr hTaskCaller, int dwTickCount, System.IntPtr
lpInterfaceInfo)
{
return 0;
}
int IOleMessageFilter.RetryRejectedCall(System.IntPtr
hTaskCallee, int dwTickCount, int dwRejectType)
{
if (dwRejectType == 2)
{
return 99;
}
return -1;
}
int IOleMessageFilter.MessagePending(System.IntPtr hTaskCallee,
int dwTickCount, int dwPendingType)
{
return 2;
}
[DllImport("Ole32.dll")]
private static extern int
CoRegisterMessageFilter(IOleMessageFilter newFilter, out
IOleMessageFilter oldFilter);
}
[ComImport(), Guid("00000016-0000-0000-C000-000000000046"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
interface IOleMessageFilter
{
[PreserveSig]
int HandleInComingCall(
int dwCallType,
IntPtr hTaskCaller,
int dwTickCount,
IntPtr lpInterfaceInfo);
[PreserveSig]
int RetryRejectedCall(
IntPtr hTaskCallee,
int dwTickCount,
int dwRejectType);
[PreserveSig]
int MessagePending(
IntPtr hTaskCallee,
int dwTickCount,
int dwPendingType);
}
}
}
If it's not broken, fix it until it is
|
|
|
|
|
Post it up as a tip, so it doesn't scroll off the page and into oblivion!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
I'm going to create a VSIX then post it here.
Many thanks
If it's not broken, fix it until it is
|
|
|
|
|
Yeah, was gonna suggest that as well! It's very useful indeed.
Best,
John
-- Log Wizard - a Log Viewer that is easy and fun to use!
|
|
|
|
|
Hi Please can you help. I have been asked to see if I can integrate our systems with a 3rd party tool.
I've had the details from the 3rd party and it turns out I need to upload some data to a JSON Web service, then obviously manipulate the results
Example php has been supplied, but I always work in c# or VB and Ive made a start but starting to feel lost, can you help ?
''
public function runJsonRequestTest() {
$client = new \SoapClient(
"https://website.wsdl",
array(
'trace' => 1,
'exception' => 0
)
);
try {
$response = json_decode(
$client->json_request(
‘username’,
‘password’,
json_encode( //The request array
[
‘category’ => ‘api’,
‘type’ => ‘getMethods’,
‘data’ => [ ]
]
)
),
true
);
}
catch(\Exception $e) {
return "Soap request failed: {$e->getMessage()}
" . $client->__getLastResponse();
}
$string = print_r($response, true);
return $String;
'''
I've also got
'''
Example request array:
[
‘category’ => ‘api’,
‘type’ => ‘getMethods’,
]
Example return output:
Array (
[status] => COMPLETE
[data] => Array (
[0] => methodA
[1] => methodB
[2] => methodC
[3] => methodD) )
'''
so far I've got the below - but I get many errors and starting to get a bit lost - the below does not compile !
'''
public class ResultsTest
{
public string status { get; set; }
public List data { get; set; }
}
public class ResultsTestList
{
public int option { get; set; }
}
public static async Task RunAsync(String Url, String Username, String Password, InstructionMessageModel instruction, String log)
{
_log = log;
_url = Url;
_username = Username;
_password = Password;
var baseAddress = new Uri(_url);
using (var client = new HttpClient())
{
client.BaseAddress = baseAddress;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var auth = string.Format("{0}:{1}", _username, _password);
var encoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);
try
{
HttpResponseMessage response = await client.PostAsJsonAsync(_url, instruction);
if (!response.IsSuccessStatusCode)
{
var errors = await response.Content.ReadAsAsync();
}
else
{
var jsonAsString = await response.Content.ReadAsAsync();
var output = JsonConvert.DeserializeObject(jsonAsString);
}
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
}
'''
|
|
|
|
|
I guess it depends if you want to transliterate the php => c# or 'do over' ie from scratch in c#.. Personally, I would
a) request the full JSON API details from the third party - this should be language independant
b) start from scratch in c#, using RestSharp, NewtonSoft JSON [tools], ...
c) I'm not sure about your POCO's for deserialising the JSON result - you have
public class ResultsTest
{
public string status { get; set; }
public List data { get; set; }
}
public class ResultsTestList
{
public int option { get; set; }
}
I dont get why ResultsTestList has 'option' in it - wouldnt it be
public class ResultsTestList
{
public List<ResultsTest> ResultsItems { get; set; }
}
ie a list of ResultsTest Objects, and I think ResultsTest should be
public class ResultsTest
{
public string status { get; set; }
public List<string> data { get; set; }
}
ie 'data' is a list of 'strings' - if you have an example of proper JSON, you can always use http://json2csharp.com/ to see what it says about the POCO's - I usually use this to start with and 'optimise' the output if I need to
looking at my point a, I dont have enough knowledge of PHP to see how it puts the call to the JSON Service together - thats why you'd be better off seeing a language independent version of the api docs - it might be as simple as {baseurl}/api/getmethods or it may not
|
|
|
|
|
Hi Thanks for your reply.
I am currently getting the error
"No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'"
on the line
var jsonAsString = await response.Content.ReadAsAsync();
so I have tried using
var jsonAsString = response.Content.ReadAsStringAsync().Result;
This does not error but I get a string value which is basically an xml exactly the same as if I browse to the url - therefore not the result I was expecting.
It is as thought im making a call to the url but not passing any information to it.
can you recommend where to look at next
thanks for your time , any help would be massively appreciated
current code is
[code]
var baseAddress = new Uri(_url);
using (var client = new HttpClient())
{
client.BaseAddress = baseAddress;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var serializer = new JavaScriptSerializer();
string testobject = serializer.Serialize(new { category = "introducerapi", type = "getMethods"});
string json = serializer.Serialize(new { username = _username, password = _password, request = testobject });
HttpResponseMessage response = await client.PostAsJsonAsync(_url, json);
if (!response.IsSuccessStatusCode)
{
}
else
{
var jsonAsString = response.Content.ReadAsStringAsync().Result;
}
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
[/code]
|
|
|
|
|
if you remember this
Quote: a) request the full JSON API details from the third party - this should be language independant
there was a reason I put it - you need to tell the API you're calling to return the result as JSON, at the moment I'd hazard its returning XML which is its default - sometimes that means putting 'format=JSON' at the end of the request - without seeing the API documentation I cant tell you how to do that - although there should be 'standards' not everyone adheres to them 
|
|
|
|
|
I've often wondered about this before but my google searches aren't revealing much.
In most modern games, you have a set of keyboard shortcuts that do various things in the game. You can generally remap these keys at runtime with ease. If you don't like pulling up the Map in the game with the 'M' key just re-map it to Tab for example.
Most of what I've found in my searches involves assigning specific keyboard keys to specific menu items, setting KeyPreview to True and having a BUST (big ugly switch statement) or some low end keyboard hook that forces you to do essentially the same thing. I'm hoping for something I bit less messy than that.
I'm wondering if anyone knows a decent library to do stuff like this. Obviously I could write something that sits there monitoring every keypress and checking for key combinations in a dictionary or something. But I'd rather not reinvent the wheel if I can help it.
Anyone have any suggestions?
Thanks a lot
E
|
|
|
|
|
Just to make sure I understand what you want:
You want to catch keys (probably by registering a keyboard hook or by RegisterHotKey), and then re-issue another key (emulate another key press)?
(if that is the case, you may have problems on Win8+, but I want to know if this is indeed what you want)
Best,
John
-- Log Wizard - a Log Viewer that is easy and fun to use!
|
|
|
|
|
I would imagine that you're going to have a dictionary of some sort in there - and you'll map that to your commands. Off the top of my head, you'd do a two phase approach to building this up. In the first phase, you'd have your application commands (looking something like this):
public class ApplicationCommand
{
public char Shortcut { get; set; }
public Action Command { get; set; }
} You would populate these as a default stage (possibly in a dictionary), and then read through some configuration to remap those elements that need to be updated:
public class CommandMap
{
private Dictionary<string, ApplicationCommand> applicationCommands = new Dictionary<string, ApplicationCommand>();
public void AddCommand(string application, ApplicationCommand command)
{
Add(application, command);
}
}
public class MyGameLoop
{
private CommandMap commandMap = new CommandMap();
public void Initialize()
{
commandMap.AddCommand("Load", new ApplicationCommand('L', ()=> { Debug.WriteLine("Loading"); }));
commandMap.AddCommand("Save", new ApplicationCommand('S', ()=> { Debug.WriteLine("Saving"); }));
}
public void UpdateEntries()
{
ConfigurationStoreReader reader = new ConfigurationStoreReader();
foreach (Tuple<string, char> element in reader.CommandUpdateMap)
{
command[element.Item1] = element.Item2;
}
}
public CommandMap Mapping { get { return command; } }
} From that, we have everything in place that we need to expose a key press to Action map
public class Game
{
private Dictionary<char, Action> actionToPerform = new Dictionary<char, Action>();
public Game(CommandMap mapping)
{
foreach (ApplicationCommand appCommand in mapping.Mapping)
{
actionToPerform.Add(appCommand.Shortcut, appCommand.Command);
}
}
public void HandleKeyPress(char keyPress)
{
if (actionToPerform.ContainsKey(keyPress))
{
actionToPerform[keyPress]();
}
}
} I've just typed this up in the web editor here, so apologies if there are minor syntactic issues but this should serve to demonstrate what I'm talking about.
This space for rent
|
|
|
|
|
Pete O'Hanlon wrote: I've just typed this up in the web editor here And it's almost ready for publication as a Tip. 
|
|
|
|
|
Thanks Richard. I enjoyed the mental challenge of keeping the moving parts in place while typing it out in the editor. It removes any distractions from the IDE and Intellisense.
This space for rent
|
|
|
|
|
I have the following dynamically added user control that is loaded during Page_Init
foreach (WSEmployerServices.PensionContributionDetail objWSPenDetailFEL in objArrXMLPensionDetails)
{
try
{
AspEmployeeDetailsPension ctlEEDPensionControl = (AspEmployeeDetailsPension)Page.LoadControl("~/AspEmployeeDetailsPension.ascx");
ctlEEDPensionControl.ID = "ctlEEDPensionControl" + objWSPenDetailFEL.PenUploadDetailId;
ctlEEDPensionControl.EEDControlLanguage = Master.MasterStrLanguage;
ctlEEDPensionControl.EEDControlResourceManager = Master.MasterResourceManager;
ctlEEDPensionControl.strIsCurrentPayroll = mobjXmlPayrollHeader.IsCurrentPayroll;
ctlEEDPensionControl.intEmpDetailId = Convert.ToInt32(objXMLPayrollEmployee.EmpUploadDetailId);
ctlEEDPensionControl.intOrgId = Convert.ToInt32(objXMLPayrollEmployee.EmployerOrgId);
ctlEEDPensionControl.intOrgStatusId = mintOrgStatusId;
ctlEEDPensionControl.intUserId = mintUserId;
ctlEEDPensionControl.intPyrllStmtId = mintPyrllStmtId;
ctlEEDPensionControl.objArrRoleAccModSelXml = mobjArrRoleAccModSelXml;
ctlEEDPensionControl.EEDPensionDetail = objWSPenDetailFEL;
ctlEEDPensionControl.SetupControl();
EEDPensionUserControlArea.Controls.Add(ctlEEDPensionControl);
}
catch (Exception ex)
{
HandleError(ex);
}
}
When I do a post back the data disappears from the control. I thought that the viewstate would repopulate the data. Any help would be very much appreciated
|
|
|
|
|
|