i tried doing this-
http://thewayithink.co.uk/post/2010/05/04/Mac-Address-in-Silverlight-4.aspx
but the 3 conditions are always false :
if ((Application.Current.IsRunningOutOfBrowser) &&
(Application.Current.HasElevatedPermissions) &&
(AutomationFactory.IsAvailable))
i guess its because of permissions and security stuff..
is there any way i can get the physical IP address off the client's side?
as i said, i use silverlight 4.
The security model of Silverlight is such that you can't access anything from the client machine outside the browser sandbox and the (small) amount of disk space allocated to isolated storage. The client machine's MAC address would fall into that category. You can however run your application "Out of Browser" (OOB) with elevated privileges which is what this test is checking for.
The first condition states that you must be running out of browser - so the first question is "Is your application OOB enabled and running out of broswer?".
If not then the test will fail.
Then if the application is running OOB it must also be running with elevated permissions. Is this the case?
As for the AutomationFactory test - the answer on this post implies that it will be true when the application is running out of browser with elevated permissions.
use this code sample which is from this link (the question is also mentioned here).
public partial class MyClient : UserControl
{
public MyClient()
{
MACAddressManager macAddressManager = new MACAddressManager();
macAddressManager.OnGetMACAddressCompleted += new EventHandler(macAddressManager_OnGetMACAddressCompleted);
macAddressManager.BeginGetMACAddress();
}
void macAddressManager_OnGetMACAddressCompleted(object sender, EventArgs e)
{
MACAddressManager manager = (MACAddressManager) sender;
// MAC Address value is in manager.MACAddress
}
}
public class MACAddressManager
{
private dynamic sWbemServices;
private dynamic sWbemSink;
public string MACAddress { get; private set; }
public event EventHandler OnGetMACAddressCompleted;
private void EndGetMACAddress(object sender, EventArgs e)
{
dynamic objWbemObject = sender;
MACAddress = objWbemObject.MACAddress;
if (OnGetMACAddressCompleted != null)
OnGetMACAddressCompleted(this, EventArgs.Empty);
}
public void BeginGetMACAddress()
{
if ((Application.Current.IsRunningOutOfBrowser) && (Application.Current.HasElevatedPermissions) && (AutomationFactory.IsAvailable))
{
dynamic sWbemLocator = AutomationFactory.CreateObject("WbemScripting.SWBemLocator");
sWbemServices = sWbemLocator.ConnectServer(".");
sWbemServices.Security_.ImpersonationLevel = 3; //impersonate
sWbemSink = AutomationFactory.CreateObject("WbemScripting.SWbemSink");
sWbemSink.OnObjectReady += new EventHandler(EndGetMACAddress);
string query = "SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true";
sWbemServices.ExecQueryAsync(sWbemSink, query);
}
}
}
Related
I have an ASP.NET Core MVC application that might be restarted from time to time (maintenance); how can make some variable values persistent from an execution to the next?
PS: That's the code that needs to write value as persistent. For example "LastMaintenanceRestartTime = 03/04-2020", the maintenance restart occurs once a day so the code needs to remember the last time it was restarted.
In UWP, I could do the following code but I can't seem to find an equivalent for ASP.NET Core:
Windows.Storage.ApplicationData.Current.LocalSettings.Values[key] = value;
The best I could find is the following code but the values are only persistent within the same execution:
AppDomain.CurrentDomain.SetData(key, value);
Some talk about "Application.Settings" but I can't seem to be able to reach this namespace...
I've also seen some people talking about "AppSettings" files that can be modified during execution but it seems rather complex to keep a simple value persistent...
Do you have any recommendation, solution or ideas for me?
I found the solution:
static void ReadSetting(string key)
{
try
{
var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key] ?? "Not Found";
Console.WriteLine(result);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
}
static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
Link: https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.appsettings?redirectedfrom=MSDN&view=dotnet-plat-ext-5.0#System_Configuration_ConfigurationManager_AppSettings
Create a model to save data and last execution time
public class ApplicationData {
public DateTime LastExecutionTime {get;set;}
public string Data {get;set;}
public bool isRunningFirstTime {get;set}
}
1.On first application run, model should be updated to current values and isRunningFirstTime should be set to false.
2. On second run, read or update values based on date and application running count
Expanding on #rashidali answer (and not saying best, but):
public class ApplicationData
{
private DateTime _lastExecutionTime;
public DateTime LastExecutionTime
{
get
{
_lastExecutionTime = (read from file/database);
return _lastExecutionTime;
}
set
{
_lastExecutionTime = value;
(write _lastExecutionTime to file/database);
}
}
public string Data {get;set;}
public bool isRunningFirstTime {get;set}
}
I have a web app that uses a request/response message in Masstransit.
This works on out test environment, no problem.
However on the customer deployment we face a problem. At the customer site we do have two network segments A and B. The component doing the database call is in segment A, the web app and the RabbitMq server in segment B.
Due to security restrictions the component in segment A has to go through a loadbalancer with a given address. The component itself can connect to RabbitMQ with Masstransit. So far so good.
The web component on segment B however uses the direct address for the RabbitMq server. When the web component now is starting the request/response call, I can see that the message arrives at the component in segment A.
However I see that the consumer tries to call the RabbitMQ server on the "wrong" address. It uses the address the web component uses to issue the request. However the component in segment A should reply on the "loadbalancer" address.
Is there a way to configure or tell the RespondAsync call to use the connection address configured for that component?
Of course the easiest would be to have the web component also connect through the loadbalancer, but due to the network segments/security setup the loadbalancer is only reachable from segment A.
Any input/help is appreciated.
I had a similar problem with rabbitmq federation. Here's what I did.
ResponseAddressSendObserver
class ResponseAddressSendObserver : ISendObserver
{
private readonly string _hostUriString;
public ResponseAddressSendObserver(string hostUriString)
{
_hostUriString = hostUriString;
}
public Task PreSend<T>(SendContext<T> context)
where T : class
{
if (context.ResponseAddress != null)
{
// Send relative response address alongside the message
context.Headers.Set("RelativeResponseAddress",
context.ResponseAddress.AbsoluteUri.Substring(_hostUriString.Length));
}
return Task.CompletedTask;
}
...
}
ResponseAddressConsumeFilter
class ResponseAddressConsumeFilter : IFilter<ConsumeContext>
{
private readonly string _hostUriString;
public ResponseAddressConsumeFilter(string hostUriString)
{
_hostUriString = hostUriString;
}
public Task Send(ConsumeContext context, IPipe<ConsumeContext> next)
{
var responseAddressOverride = GetResponseAddress(_hostUriString, context);
return next.Send(new ResponseAddressConsumeContext(responseAddressOverride, context));
}
public void Probe(ProbeContext context){}
private static Uri GetResponseAddress(string host, ConsumeContext context)
{
if (context.ResponseAddress == null)
return context.ResponseAddress;
object relativeResponseAddress;
if (!context.Headers.TryGetHeader("RelativeResponseAddress", out relativeResponseAddress) || !(relativeResponseAddress is string))
throw new InvalidOperationException("Message has ResponseAddress but doen't have RelativeResponseAddress header");
return new Uri(host + relativeResponseAddress);
}
}
ResponseAddressConsumeContext
class ResponseAddressConsumeContext : BaseConsumeContext
{
private readonly ConsumeContext _context;
public ResponseAddressConsumeContext(Uri responseAddressOverride, ConsumeContext context)
: base(context.ReceiveContext)
{
_context = context;
ResponseAddress = responseAddressOverride;
}
public override Uri ResponseAddress { get; }
public override bool TryGetMessage<T>(out ConsumeContext<T> consumeContext)
{
ConsumeContext<T> context;
if (_context.TryGetMessage(out context))
{
// the most hackish part in the whole arrangement
consumeContext = new MessageConsumeContext<T>(this, context.Message);
return true;
}
else
{
consumeContext = null;
return false;
}
}
// all other members just delegate to _context
}
And when configuring the bus
var result = MassTransit.Bus.Factory.CreateUsingRabbitMq(cfg =>
{
var host = cfg.Host(new Uri(hostAddress), h =>
{
h.Username(...);
h.Password(...);
});
cfg.UseFilter(new ResponseAddressConsumeFilter(hostAddress));
...
});
result.ConnectSendObserver(new ResponseAddressSendObserver(hostAddress));
So now relative response addresses are sent with the messages and used on the receiving side.
Using observers to modify anything is not recommended by the documentation, but should be fine in this case.
Maybe three is a better solution, but I haven't found one. HTH
I am creating a sample project for learning purpose(later on I will be working on project based on webrtc and kurento), I am using Kurento media server with it, I have modified the tutorial of the kurento server and made one sample out of it.
In all of the samples for Kurento Server they are using a UserRegistry.java where they are storing objects of UserSession as shown below:
public class UserSession {
private static final Logger log = LoggerFactory.getLogger(UserSession.class);
private final String name;
private final WebSocketSession session;
private String sdpOffer;
private String callingTo;
private String callingFrom;
private WebRtcEndpoint webRtcEndpoint;
private WebRtcEndpoint playingWebRtcEndpoint;
private final List<IceCandidate> candidateList = new ArrayList<>();
public UserSession(WebSocketSession session, String name) {
this.session = session;
this.name = name;
}
public void sendMessage(JsonObject message) throws IOException {
log.debug("Sending message from user '{}': {}", name, message);
session.sendMessage(new TextMessage(message.toString()));
}
public String getSessionId() {
return session.getId();
}
public void setWebRtcEndpoint(WebRtcEndpoint webRtcEndpoint) {
this.webRtcEndpoint = webRtcEndpoint;
if (this.webRtcEndpoint != null) {
for (IceCandidate e : candidateList) {
this.webRtcEndpoint.addIceCandidate(e);
}
this.candidateList.clear();
}
}
public void addCandidate(IceCandidate candidate) {
if (this.webRtcEndpoint != null) {
this.webRtcEndpoint.addIceCandidate(candidate);
} else {
candidateList.add(candidate);
}
if (this.playingWebRtcEndpoint != null) {
this.playingWebRtcEndpoint.addIceCandidate(candidate);
}
}
public void clear() {
this.webRtcEndpoint = null;
this.candidateList.clear();
}
}
I have two questions on this:
Why do we need session object?
What are the alternatives(if there are any) to manage session?
Let me give some more background on 2nd question. I found out that I can run the Kurento-JavaScript-Client(I need to convert it to browser version and then I can use it.) on the client side only (That way I won't require a backend server i.e. nodejs or tomcat - this is my assumption). So in this case how would I manage session or I can totally remove the UserRegistry concept and use some other way.
Thanks & Regards
You need to store sessions to implement signalling between the clients and the application server. See for example here. The signalling diagram describes the messages required to start/stop/etc the WebRTC video communication.
If you are planing to get rid of the application server (i.e. move to JavaScript client completely) you can take a look to a publish/subscribe API such as PubNub.
Hey i want when user is trying to un-install an app ,there comes password to unlock. Im following this code :
android: require password when uninstall app
but there comes an error in manifest "android:description="#string/descript""
Kindly help me.im badly stuck in it.there's no answer availble on google too
it would not help on 4.3 or higher but I am posting a link where you can find the solution and reason of why you can not do it.
Here is the link. Hope it would help you in understanding the real milestone in this context.
try the following code in your service
public static final String UNINSTALLER ="com.android.packageinstaller.UninstallerActivity";
private ActivityManager activityManager = null;
private ExecutorService executorService;
#Override
public void onCreate() {
super.onCreate();
executorService = Executors.newSingleThreadExecutor();
activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
LockerThread thread = new LockerThread();
executorService.submit(thread);
}
private void protactApp(String packname) {
Intent pwdIntent = null;
pwdIntent = new Intent("uninstaller.receiver");
sendBroadcast(pwdIntent);
}
class LockerThread implements Runnable {
private String lastname;
public LockerThread() {
}
#Override
public void run() {
ComponentName act = activityManager.getRunningTasks(1).get(0).topActivity;
String packname = act.getPackageName();
if (act.getClassName().equals(UNINSTALLER)) {
Log.d("Tag", "package to be uninstalled");
protactApp(UNINSTALLER);
}
}
and from receiver you can get action while uninstall the app so whatever screen you prepare for password or pattern that you can start before uninstall like applock application
I'm trying to run a self hosted executable as a Windows service. I'm using the MVC 4 beta Web API. First I used Derik Whittaker's blog for setting up the basic console application and tested it with positive results.
I then used Einar Egilsson's blog to make it work as both a console application and a windows service. The application installed as a service just fine. I set the service logon to use my own for this basic testing; it failed to bind to the socket without this. When the service starts up I see all my trace logs as expected there are no fatal errors. The application appears to be running normally. When I test using fiddler using the same request for the console application I get a "HTTP/1.1 500 Internal Server Error".
Using this same code when I turn off the service then launch using F5 in VS the application starts up just fine and serves the same request!? The log entries are identical within the same execution paths.
public partial class TestService : ServiceBase {
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private HttpSelfHostServer _server;
static void Main(string[] args) {
Logger.Debug("Main Called");
var service = new TestService();
if (Environment.UserInteractive) {
Logger.Debug("Environment.UserInteractive == true");
Console.WriteLine("Press any key to stop program");
service.OnStart(args);
service.OnStop();
} else {
Logger.Debug("Environment.UserInteractive == false");
try {
Run(service);
} catch(Exception exception) {
Logger.Fatal(exception.Message, exception);
}
}
}
protected override void OnStart(string[] args) {
Logger.Debug("OnStart called");
var hostUri = string.Format("http://{0}:{1}", Environment.MachineName, ConfigurationManager.AppSettings["Service.Port"]);
Logger.Debug("URL:" + hostUri);
var selfHostConfiguration = new HttpSelfHostConfiguration(hostUri);
selfHostConfiguration.Routes.MapHttpRoute(
name: "DefaultApiRoute",
routeTemplate: "endpoints/{controller}",
defaults: null
);
Logger.Debug("Routes registered");
try {
using (_server = new HttpSelfHostServer(selfHostConfiguration)) {
Logger.Debug("Hosting at " + hostUri + "/endpoints/{controller}");
_server.OpenAsync().Wait();
if (Environment.UserInteractive) { // *** I've tried this commented out as well
Console.ReadLine();
}
Logger.Debug("End of using");
}
} catch(Exception exception) {
Logger.Fatal(exception.Message, exception);
if(exception.InnerException != null) {
Logger.Fatal(exception.InnerException.Message, exception.InnerException);
}
}
}
protected override void OnStop() {
_server.Dispose();
}
}
It has been some time since you posted this but I wanted to input.
I don't know why this is, but the internal error comes from initializing the self host inside the onStart method. You must initialize it in the constructor of the service and then only call the _server.OpenAsync() in the onStart method.
Or at least that is what worked for me.
Use TopShelf. I just blogged about how to do that.
as i can see, you use _server.OpenAsync().Wait(); in OnStart method. This just makes your initialization code to freeze, all code after that line will not execute. To avoid this try to remove .Wait() from the OpenAsync().