UnauthorizedAccessException in Webcam app - windows-8

I'm trying to make a simple webcam app:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.MediaProperties;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
namespace App1
{
public sealed partial class MainPage : Page
{
private Windows.Media.Capture.MediaCapture m_mediaCaptureMgr;
private Windows.Storage.StorageFile m_photoStorageFile;
private readonly String PHOTO_FILE_NAME = "photo.jpg";
public MainPage()
{
this.InitializeComponent();
}
internal async void initializeCamera()
{
m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
await m_mediaCaptureMgr.InitializeAsync();
statusBox.Text = "initialized";
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
internal async void takePicture(object sender, RoutedEventArgs e)
{
m_photoStorageFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(PHOTO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
await m_mediaCaptureMgr.CapturePhotoToStorageFileAsync(imageProperties, m_photoStorageFile);
}
private void initializeButton(object sender, RoutedEventArgs e)
{
initializeCamera();
}
}
}
However, when I click on the initializeButton, I got an exception:
UnauthorizedAccessException (Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)))
What could be the problem here?
EDIT: I found the bug. Basically, if the webcam is already initialized, trying to initialize it again will trigger an exception. So I had to put in a flag, and some try/catch

Have you set the capabilities for Microphone and Webcam in the manifest file?

Seect the Microphone and Webcam capability in Package.Appmnifest file

Related

Injecting DBcontext file Azure Function (Http trigger)

I am trying to connect my azure function to a local DB using Entity frameworkcore code 1st but I keep on getting this error when I try to add migrations,
Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.b__13()
but I am using the same connection string i use for all my app, just a different DB
This is my context file
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace FunctionApp36
{
class BookContext :DbContext
{
public BookContext(DbContextOptions<BookContext> options) : base(options)
{
}
public BookContext(DbContextOptions options) : base(options)
{
}
public BookContext() : base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlServer("Data Source=ABS\\SQLEXPRESS;Initial Catalog=Ba;Integrated Security=True");
}
}
and this is my startup file
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using FunctionApp36;
[assembly: WebJobsStartup(typeof(StartUp))]
namespace FunctionApp36
{
public class StartUp : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
var config = new ConfigurationBuilder()
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
builder.Services.AddDbContext<BookContext>(options1 =>
{
options1.UseSqlServer(
config["ConnectionStrings:DefaultConnection"],
builder =>
{
builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
builder.CommandTimeout(10);
}
);
});
}
}
}
DbContextPool needs single public constructor.
You either need to use AddDbContext or AddDbContextPool, not both of them.
Check my Example below and try:
public partial class MyDbContext : DbContext
{
private readonly ... //Code
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
//Code
}
}
For more information, please refer this MSFT documentation

Xamarin forms how to keep label text value after navigation

On my Main Page, I will set my label text (#lblStartDateTime) to current time stamp when user click on a button. It will navigate to Second Page, and once I click "done" button, it will go back to Main Page.
When I navigate back to Main Page from Second Page, my label text disappeared. Does anyone know how to keep the label text value after navigation?
Main Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Test
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage: ContentPage
{
public string previouspagevalue;
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
lblEndDT.Text = previouspagevalue;
}
private void btnOffline_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new SecondPage());
string currentDT = DateTime.Now.ToString();
lblStartDT.Text = currentDT;
}
}
}
Second Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Test
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SecondPage: ContentPage
{
public SecondPage()
{
InitializeComponent();
}
protected void btnDone_Clicked(object sender, EventArgs e)
{
MainPage mainpage = new MainPage();
string edt = DateTime.Now.ToString();
lblEndDateTime.Text = edt;
mainpage.previouspagevalue = lblEndDateTime.Text;
Navigation.PushAsync(mainpage);
}
}
}
In you btnDone_Clicked event , you should use Navigation.PopAsync to go back to MainPage, Navigation.PushAsync(mainpage); means to go to a new MainPage not the previous Page.
protected void btnDone_Clicked(object sender, EventArgs e)
{
Navigation.PopAsync();
}
Please read document to learn about how NavigationPage works.
Update, you can pass the value you need to the SecondPage when you push to SecondPage:
Codes in MainPage:
public partial class MainPage : ContentPage
{
public string previouspagevalue;
public MainPage()
{
InitializeComponent();
previouspagevalue = "I'm previouspagevalue";
}
protected override void OnAppearing()
{
base.OnAppearing();
//if you set the lblEndDT.Text = "someValue"; in the secondPage, there is no need to update it here
lblEndDT.Text = previouspagevalue;
}
private void btnOffline_Clicked(object sender, EventArgs e)
{
//Pass the parametere you need when you go to SecondPage
Navigation.PushAsync(new SecondPage(this, lblEndDT));
string currentDT = DateTime.Now.ToString();
lblStartDT.Text = currentDT;
}
}
SecondPage:
public partial class SecondPage : ContentPage
{
Label MainPagelblEndDT;
MainPage mainPage;
public SecondPage()
{
InitializeComponent();
}
public SecondPage(MainPage mainP,Label lblEndDT)
{
InitializeComponent();
//Get the lblEndDT reference here
MainPagelblEndDT = lblEndDT;
//Get the MainPage reference here
mainPage = mainP;
}
private void Button_Clicked(object sender, EventArgs e)
{
string edt = DateTime.Now.ToString();
//Use it
MainPagelblEndDT.Text = edt;
mainPage.previouspagevalue = MainPagelblEndDT.Text;
Navigation.PopAsync();
}
}
I uploaded a sample project here and you can check it. Feel free to ask me any question if you have.
I would suggest you wrap your pages in a navigation stack, use a NavigationPage and navigate to next page then when you pop back it will maintain your state.
In your App.xaml.cs
MainPage = new NavigationPage(new YourFirstPage);
Then push a page into the navigation and when you want to go back just do a
Navigation.PopAsync();
Goodluck
Feel free to get back if you have queries

Multiple browser instance launch when i execute my test

I an new in specflow i am implementing framework. When i create one feature file with multiple scenario and execute my test than it open one browser instance and run successful when i add one more feature file with multiple scenario and execute my test than it launch multiple browser instance one instance for each scenario can anyone help me out what's wrong in my code
Start.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;
namespace Orange_HRM
{
class Start : SeleniumDriver
{
[BeforeScenarioBlock]
public void Setup()
{
Intitialize();
WebDriver.Navigate().GoToUrl(BaseAddress);
}
[AfterScenarioBlock]
public void TearDown()
{
Close();
}
}
}
SeleniumDriver.cs
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Orange_HRM
{
class SeleniumDriver
{
public static IWebDriver WebDriver;
public static string BaseAddress
{
get { return Constants.Url; }
}
public static void Intitialize()
{
WebDriver = new ChromeDriver();
WebDriver.Manage().Window.Maximize();
TurnOnWait();
}
public static void Navigate()
{
WebDriver.Navigate().GoToUrl(BaseAddress);
}
public static void Close()
{
WebDriver.Close();
}
public static void Quit()
{
WebDriver.Quit();
}
private static void TurnOnWait()
{
WebDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
WebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromMinutes(2);
}
}
}
You are using SpecFlow of techtalk.
Concept name is Hooks.
to perform automatic logic operations at specific timings.So, hooks are event bindings.
running tests in multiple threads with SpecFlow+ Runner.
So, you can put orders,
class Start : SeleniumDriver
{
[BeforeScenario(Order = 0)]
public void Setup()
{
Intitialize();
WebDriver.Navigate().GoToUrl(BaseAddress);
}
[BeforeScenario(Order = 1)]
public void TearDown()
{
Close();
}
}
i like to suggest you dont use them, Bindings Class without Hooks.
i.e. [BeforeTestRun] [AfterTestRun] use them instead.
[AfterScenario]
public void CleanUp()
{
if (seleniumDriver != null)
{
SeleniumDriver.Dispose();
seleniumDriver = null;
}
}
You can initialise and close the driver at Test Run level instead of scenario level. And maintain the url navigation alone at Scenario level. So that the driver will be initiated before test starts and quit after the test completes. Also the page will get refreshed before each scenario run.
namespace Orange_HRM
{
class Start : SeleniumDriver
{
[BeforeTestRun]
public static void Setup()
{
Intitialize();
}
[AfterTestRun]
public static void TearDown()
{
Quit();
}
[AfterScenarioBlock]
public void navigateToUrl()
{
WebDriver.Navigate().GoToUrl(BaseAddress);
}
}
}
Also you have used WebDriver.Close() instead WebDriver.Quit(). If we use WebDriver.Close() for the main window, then session will be terminated. Then if we try to access the same webdriver object again, it will throw No such session error.
WebDriver.Close() is meant for closing child window if we are working with mulitple windows. So to close main window, we have to use WebDriver.Quit() directly.

integrate vivotek ip camera in C# windows application using VitaminCtrl

i develop a application to get video from vivotek ip camera the code is given below but it shows connecting to 10.60.13.12... video is not received
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VITAMINDECODERLib;
using AxVITAMINDECODERLib;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnconnect_Click_1(object sender, EventArgs e)
{
string strPreIP = "http://";
if (txtip.TextLength != 0)
axVitaminCtrl1.Url = strPreIP + txtip.Text;
// Port
axVitaminCtrl1.HttpPort = Convert.ToInt32(txtport.Text);
// User name
if (txtusername.TextLength != 0)
axVitaminCtrl1.UserName = txtusername.Text;
// Password
if (txtpass.TextLength != 0)
axVitaminCtrl1.Password = txtpass.Text;
// View stream
axVitaminCtrl1.ViewStream = (VITAMINDECODERLib.EDualStreamOption)comboviewstream.SelectedIndex.GetHashCode();
// Protocol
axVitaminCtrl1.ConnectionProtocol = (VITAMINDECODERLib.EConnProtocol)comboprotocol.SelectedIndex.GetHashCode() + 1;
axVitaminCtrl1.Connect();
}
private void button1_Click(object sender, EventArgs e)
{
axVitaminCtrl1.Disconnect();
}
private void comboviewstream_SelectedIndexChanged(object sender, EventArgs e)
{
axVitaminCtrl1.ViewStream = (VITAMINDECODERLib.EDualStreamOption)((System.Windows.Forms.ComboBox)sender).SelectedIndex.GetHashCode();
}
private void axVitaminCtrl1_OnVideoCodec(object sender, _IVitaminCtrlEvents_OnVideoCodecEvent e)
{
e.eVideoCodec = VITAMINDECODERLib.EVideoCodecType.eViCodecMJpeg;
}
}
}
You should check debug/release platform (change it to x86)
Your pc that run this program and the camera should have same subnet

NHibernate.HibernateException: No session bound to the current context

i'm working in a new project and i'm trying to implement nhibernate with ninject in asp.net mvc. I'm having the error:
NHibernate.HibernateException: No session bound to the current context
Below is the code i'm using:
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions.Helpers;
using NHibernate;
using NHibernate.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestNhibernateSessions
{
public class SessionFactory : IHttpModule
{
private static readonly ISessionFactory _SessionFactory;
static SessionFactory()
{
_SessionFactory = CreateSessionFactory();
}
public void Init(HttpApplication context)
{
context.BeginRequest += BeginRequest;
context.EndRequest += EndRequest;
}
public void Dispose()
{
}
public static ISession GetCurrentSession()
{
return _SessionFactory.GetCurrentSession();
}
private static void BeginRequest(object sender, EventArgs e)
{
ISession session = _SessionFactory.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
private static void EndRequest(object sender, EventArgs e)
{
ISession session = CurrentSessionContext.Unbind(_SessionFactory);
if (session == null) return;
try
{
session.Transaction.Commit();
}
catch (Exception)
{
session.Transaction.Rollback();
}
finally
{
session.Close();
session.Dispose();
}
}
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection")))
.Mappings(m => m.AutoMappings.Add(CreateMappings()))
.CurrentSessionContext<WebSessionContext>()
.BuildSessionFactory();
}
private static AutoPersistenceModel CreateMappings()
{
return AutoMap
.Assembly(System.Reflection.Assembly.GetCallingAssembly())
.Where(t => t.Namespace != null && t.Namespace.EndsWith("Domain"))
.Conventions.Setup(c => c.Add(DefaultCascade.SaveUpdate()));
}
}
}
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(TestNhibernateSessions.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(TestNhibernateSessions.App_Start.NinjectWebCommon), "Stop")]
namespace TestNhibernateSessions.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using TestNhibernateSessions.Repository;
using TestNhibernateSessions.Service;
using NHibernate;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IProductRepository>().To<ProductRepository>();
kernel.Bind<IProductService>().To<ProductService>();
}
}
}
Since you're using Ninject, my recommendation is to use it to inject the session factory rather than an IHttpModule. To do so, create Ninject Provider classes as shown below. Note that this requires transaction management in code, I dislike the idea of blindly holding a transaction open during a request.
public class SessionFactoryProvider : Provider<ISessionFactory>
{
protected override ISessionFactory CreateInstance(IContext context)
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection")))
.Mappings(m => m.AutoMappings.Add(CreateMappings()))
.CurrentSessionContext<WebSessionContext>()
.BuildSessionFactory();
}
}
public class SessionProvider : Provider<ISession>
{
protected override ISession CreateInstance(IContext context)
{
var sessionFactory = context.Kernel.Get<ISessionFactory>();
var session = sessionFactory.OpenSession();
session.FlushMode = FlushMode.Commit;
return session;
}
}
Then in NinjectWebCommon:
private static void RegisterServices(IKernel kernel)
{
// session factory instances are singletons
kernel.Bind<ISessionFactory>().ToProvider<SessionFactoryProvider>().InSingletonScope();
// session-per-request
kernel.Bind<ISession>().ToProvider<SessionProvider>().InRequestScope();
}