i have a method in a Usercontrol with this code
public bool GetActiveDocument(ref EnvDTE.Document doc)
{
try
{
var dte = (DTE2)GetService(typeof(SDTE));
doc = dte.ActiveDocument;
if (doc == null)
{
MessageBox.Show("There isn't any file open in the Code Editor");
return false;
}
else return true;
}
catch (Exception)
{
MessageBox.Show("There was a problem getting the actual file, verify if it is open");
return false;
}
}
I want to move this method to a "Proxy" class that is going to act as an intermediary between Visual Studio and my application. The problem is that GetService only return the active document correctly if it is call inside the control. When i move that method to the Proxy class, GetService doesn't have definition. I search that this method comes from ComponentModel.Component, so i made the Proxy class derive from Component. Everything compiles OK but always when i ask for the active document an exception occurs. I thing that i'm not understanding well how works the GetService() method. Please help with this.
Component.GetService invokes IServiceProvider.GetService on the ISite instance assigned to the component's Site property (assuming there is one). You shouldn't need to make your proxy instance inherit from Component, but you will need to give it access to the ISite/IServiceProvider.
Related
I have a method inside MVC Controller which is called from href inside anchor tag.
public ActionResult DoSomething(string value)
{
if(true)
{
return new RedirectResult("http://google.com");
}
}
when I debug and hit that method Response.Redirect does nothing no exceptions either. any ideas?
Thanks in advance!
Use Redirect
return Redirect("http://www.google.com");
Response.Redirect is not preferred way of doing redirects in asp.net mvc
Response.Redirect and ASP.NET MVC – Do Not Mix
Update: It seems that you are trying to redirect ajax request. If you redirect ajax request, your main page won't be redirected.
There are a few things you need to do here to avoid all these issues.
Starting with the AJAX errors you're getting, they most like relate to the javascript debugger, which Microsoft refer to as "BrowserLink".
If you use Firefox or Chrome, this feature simply doesn't work, which is probably the easiest way to avoid the issue, however you can disable the feature here:
You can change the default browser to run the website in just to the left.
In terms of Response.Redirect, I think that's been well covered, you should use return Redirect() instead, however your code needs to be refactored to allow for that.
Assuming that method is a helper method which is required to be separate from the controller itself, there are a couple of main approaches to doing what you're trying to to do.
1) Magic Values
This could include "redirect1" or also commonly null, and would look something like:
public ActionResult MyAction
{
string data = ProcessString("some data");
if (data == null) { return Redirect("google.com"); }
}
public string ProcessString(string input)
{
if (condition) { return null; }
string output = input + "!"; // or whatever you need to do!
return input;
}
2) Handle via exceptions
Assuming the problem is that the data is in some way bad, and you want to redirect away because you cant process it, Exception handling is most likely the way to go. It also allows for different types of exceptions to be raised by a single method and handled independently without having magic values which then can't be used as normal data.
public ActionResult MyAction
{
string data; // remember this will be null, not "" by default
try
{
data = ProcessString("some data");
}
catch (OwlMisalignedException ex)
{
return RedirectToAction("Index", "Error", new { exData = ex.Code });
}
// proceed with controller as normal
}
public string ProcessString(string input)
{
if (condition)
{
throw new OwlMisalignedException(1234);
// this is (obviously) a made up exception with a Code property
// as an example of passing the error code back up to an error
// handling page, for example.
}
string output = input + "!"; // or whatever you need to do!
return input;
}
By using that approach you can effectively add extra return states to methods without having to fiddle with your return type or create loads of magic values.
Don't use throw Exception - either use one of the more specific types ArgumentException and ArgumentNullException will probably come in handy, or create your own types if needs be.
You'll find info on creating your own Exception types on here easily enough.
I am trying to serialse a fingerprint FMD to XML using the code below, but get an error:
Error: DPUruNet.DataResult`1[DPUruNet.Fmd] cannot be serialized
because it does not have a parameterless constructor.
public void storePrint(DataResult<Fmd> resultConversion)
{
//store fingerprint as byte and insert to server------------
using (StreamWriter myWriter = new StreamWriter("test.txt", false))
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(resultConversion.GetType());
x.Serialize(myWriter, resultConversion);
}
MessageBox.Show("Fingerprint Stored!");
//------------------------------------------------------------
}
private void OnCaptured(CaptureResult captureResult)
{
try
{
// Check capture quality and throw an error if bad.
if (!_sender.CheckCaptureResult(captureResult)) return;
count++;
DataResult<Fmd> resultConversion = FeatureExtraction.CreateFmdFromFid(captureResult.Data, Constants.Formats.Fmd.ANSI);
SendMessage(Action.SendMessage, "A finger was captured. \r\nCount: " + (count));
if (resultConversion.ResultCode != Constants.ResultCode.DP_SUCCESS)
{
_sender.Reset = true;
throw new Exception(resultConversion.ResultCode.ToString());
}
preenrollmentFmds.Add(resultConversion.Data);
//--------------------CALL METHOD
storePrint(resultConversion);
//
The class DataResult is being referenced, so I can not alter it
UPDATE
If you don't have access to the DataResult<T> class, then you might have to take a slightly different approach and wrap this class with a different, serializable one. You can find a full example here:
How can I XML Serialize a Sealed Class with No Parameterless Constructor?
Previous Answer
The error is clear; you just need to add a parameterless constructor to the DataResult<T> class:
public class DataResult<T>
{
// Add a default constructor (public visibility, no parameters)
public DataResult()
{
// You can still define a method body if you wish,
// no restrictions there. Just don't do anything that
// could jeopardize the (de)serialization.
}
}
As for the implications of adding a default constructor, without knowing what
FeatureExtraction.CreateFmdFromFid(...)
is doing to create the DataResult<Fmd>, it would be impossible to know whether it would cause any issues.
Thanks to Cory, that is a useful answer, however in this example there is another way of serializing using
tempFingerPrint = Fmd.SerializeXml(resultConversion.Data);
this is specific to the Digital Persona SDK
I want to create engine for extensions, right now I have a basic class called "Module" which contains lot of virtual functions, each extension is a class that inherits "Module" and override the functions (mostly hooks) with own code.
I want to be able to put these extensions to separate binary and to load it "on the fly".
I created a simple handler for loading these plugins:
public static bool LoadMod(string path)
{
try
{
if (File.Exists(path))
{
System.Reflection.Assembly library = System.Reflection.Assembly.LoadFrom(path);
if (library == null)
{
Program.Log("Unable to load " + path + " because the file can't be read", true);
return false;
}
Type[] types = library.GetTypes();
Type type = library.GetType("wmib.RegularModule");
Type pluginInfo = null;
foreach (Type curr in types)
{
if (curr.IsAssignableFrom(type))
{
pluginInfo = curr;
break;
}
}
if (pluginInfo == null)
{
Program.Log("Unable to load " + path + " because the library contains no module", true);
return false;
}
Module _plugin = (Module)Activator.CreateInstance(pluginInfo);
return true;
}
}
catch (Exception fail)
{
core.handleException(fail);
}
return false;
}
My problem is that these modules are calling functions in static classes that I have in host application. Is it possible to create some "skeleton" of this static class in source code of extension? I tried creating the class in the second source code with empty functions of same name and parameters, but that doesn't work for some reason (every time I attempt to load it I get: Exception has been thrown by the target of an invocation.mscorlib at System.Reflection.MonoCMethod.Invoke)
Here is example of what I want to be able to do:
There is a host application that contains extension handler, and some own static functions.
The host application loads the module from binary file and insert it to some array of modules (this is what is done in constructor of every class that inherits "Module". This module contains some functions which are calling the static functions of host application. What I need to be able to do is being able to call the static function that is defined in source code of host application, even in source code of plugin, which doesn't contain the static function's code. I hope it's clear a bit :)
Ok, it's actually not that hard as I thought, I just referenced the host binary to extension, which enabled all static elements and classes of host in the extension.
I'm having trouble with some syntax. I'm not really familiar with interfaces so please excuse my ignorance.
VS2010 is giving me an error at... application.Name = System.AppDomain.CurrentDomain.FriendlyName;
public static void AddApplication(string applicationName = null, string processImageFileName = null)
{
INetFwAuthorizedApplications applications;
INetFwAuthorizedApplication application;
if(applicationName == null)
{
application.Name = System.AppDomain.CurrentDomain.FriendlyName;/*set the name of the application */
}
else
{
application.Name = applicationName;/*set the name of the application */
}
if (processImageFileName == null)
{
application.ProcessImageFileName = System.Reflection.Assembly.GetExecutingAssembly().Location; /* set this property to the location of the executable file of the application*/
}
else
{
application.ProcessImageFileName = processImageFileName; /* set this property to the location of the executable file of the application*/
}
application.Enabled = true; //enable it
/*now add this application to AuthorizedApplications collection */
Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
applications = (INetFwAuthorizedApplications)mgr.LocalPolicy.CurrentProfile.AuthorizedApplications;
applications.Add(application);
}
I can make that error go away by setting application to null but that causes a run-time null reference error.
Edit:
Here's where I'm adapting the code from. I hope it gives more context
http://blogs.msdn.com/b/securitytools/archive/2009/08/21/automating-windows-firewall-settings-with-c.aspx
You never initialize
application
before using it here:
application.Name = System.AppDomain.CurrentDomain.FriendlyName;
The variable application is defined as:
INetFwAuthorizedApplication application
You need to assign an instance of a class that implements the interface INetFwAuthorizedApplication.
Somewhere there must be one (or probably more) classes in your project that look something like this:
public class SomeClass : INetFwAuthorizedApplication
{
// ...
}
public class AnotherClass : INetFwAuthorizedApplication
{
// ...
}
You need to determine what class you should use (SomeClass, AnotherClass) then assign an appropriate object, e.g. like this:
INetFwAuthorizedApplication application = new SomeClass();
Interfaces are used to describe what an object does, not what it is specifically. To put into "real world" terms, an interface might be like:
ISmallerThanABreadbox with a FitIntoBreadbox() method. I can't ask you to give me "the smaller than a breadbox" ... as that doesn't make any sense. I can only ask you to give me something that "IS smaller than a breadbox". You have to come up with your own object that makes sense to have the interface on it. An apple is smaller than a breadbox, so if you have a breadbox that only holds items smaller than it, an apple is a good candidate for the ISmallerThanABreadbox interface.
Another example is IGraspable with a Hold() method and FitsInPocket bool property. You can ask to be given something that IS graspable that may or may not fit in your pocket, but you can't ask for "the graspable".
Hope that helps...
I'm calling a C# COM component using javascript: keystore = new ActiveXObject("RBCrypto.KeyStore");. I've noticed this instance stays around until I exit the browser. Is there anyway to "release" that object when the user leaves the page? Currently i'm using:
window.onunload=function() //when a user leaves the page close the keystore
{
if(keystore != null)
{
try
{
keystore.closeKeyStore(); //method in keystore
delete keystore;
}
catch(err) { alert(err.description); }
}
}
But the COM object is still hangin around. Any ideas?
I know it's a little late to respond. "Before late than never"
I think the correct is "Application.Quit();". However, the Application of object COM/OLE/ActiveX can return null. I do not know how to do return Application != null to run the Quit();
You can try...
try
{
keystore.closeKeyStore();
delete keystore;
keystore = null;
CollectGarbage();
}
catch(err)
{
alert('freeing ActiveXObject via javascript'+ err.description);
}
try,
keystore.Application.Quit();
This result is from http://www.c-point.com/javascript_tutorial/jsobjActiveXObject.htm
you can also try nulling all the object attached values before delete
for (k in elm) {
try {
elm[k] = null;
}
catch (e) {
}
}
}
I have found this helps in the case of HTML objects that have not been delete, and have various objects attached to them.