问:
Error "cannot find the file specified" when connecting to Azure SQL
I have developed an ASP.NET application which I deployed on Azure. I did connect my program to a database (and properly changed the Connection String). I followed this tutorial until the migration part, and yet I have the following error:</p>

```<code>The system cannot find the file specified
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:
[Win32Exception (0x80004005): The system cannot find the file specified]

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)]
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) +1081
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +803
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +38
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +739
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +85
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +449
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +108
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +935
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +143
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +17
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +139
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +448
   System.Data.SqlClient.SqlConnection.Open() +129
   System.Data.Entity.Infrastructure.Interception.<>c.<Open>b__13_0(DbConnection t, DbConnectionInterceptionContext c) +12
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
   System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +424
   System.Data.Entity.SqlServer.<>c__DisplayClass60_0.<UsingConnection>b__0() +426
   System.Data.Entity.SqlServer.<>c__DisplayClass2_0.<Execute>b__0() +10
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +189
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) +78
   System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act) +175
   System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act) +552
   System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +90
   System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) +173
   System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) +76
   System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase() +134
   System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) +119
   System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +142
   System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +78
   System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext) +89
   System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState) +116
   System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +218
   System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) +138
   System.Data.Entity.Internal.<>c__DisplayClass66_0`1.<CreateInitializationAction>b__0() +76
   System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +60
   System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +357
   System.Data.Entity.Internal.<>c.<InitializeDatabase>b__58_0(InternalContext c) +9
   System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +129
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +196
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +86
   System.Data.Entity.Internal.InternalContext.Initialize() +30
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
   System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
   System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +38
   System.Linq.Queryable.OrderBy(IQueryable`1 source, Expression`1 keySelector) +83
   ProiectLicenta.Controllers.Main.ActorController.Index() in C:\ProiectLicenta\ProiectLicenta\Controllers\Main\ActorController.cs:25
   lambda_method(Closure , ControllerBase , Object[] ) +62
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +169
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
   System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
   System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
   System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
   System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +577
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +132
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
</code>```

答:
Apparently changing the Connection String didn't propagate, since you're getting an error that states

provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.

This means it's trying to connect to a LocalDB/SQL Server Express instance instead of trying to connect to an Azure SQL database.

A couple of things you can try:

Check for any hardcoded connection strings

Make sure the right connection string with the right name is available in Application Settings

Restart the App Service to make sure the new connection string is retrieved

Body:
I have developed an ASP.NET application which I deployed on Azure. I did connect my program to a database (and properly changed the Connection String). I followed this tutorial until the migration part, and yet I have the following error:

The system cannot find the file specified
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:
[Win32Exception (0x80004005): The system cannot find the file specified]

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)]
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) +1081
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +803
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +38
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +739
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +85
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +449
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +108
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +935
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +143
   System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +17
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +139
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +448
   System.Data.SqlClient.SqlConnection.Open() +129
   System.Data.Entity.Infrastructure.Interception.<>c.<Open>b__13_0(DbConnection t, DbConnectionInterceptionContext c) +12
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
   System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +424
   System.Data.Entity.SqlServer.<>c__DisplayClass60_0.<UsingConnection>b__0() +426
   System.Data.Entity.SqlServer.<>c__DisplayClass2_0.<Execute>b__0() +10
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +189
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) +78
   System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act) +175
   System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act) +552
   System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +90
   System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) +173
   System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) +76
   System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase() +134
   System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) +119
   System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +142
   System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +78
   System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext) +89
   System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState) +116
   System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +218
   System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) +138
   System.Data.Entity.Internal.<>c__DisplayClass66_0`1.<CreateInitializationAction>b__0() +76
   System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +60
   System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +357
   System.Data.Entity.Internal.<>c.<InitializeDatabase>b__58_0(InternalContext c) +9
   System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +129
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +196
   System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +86
   System.Data.Entity.Internal.InternalContext.Initialize() +30
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
   System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
   System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +38
   System.Linq.Queryable.OrderBy(IQueryable`1 source, Expression`1 keySelector) +83
   ProiectLicenta.Controllers.Main.ActorController.Index() in C:\ProiectLicenta\ProiectLicenta\Controllers\Main\ActorController.cs:25
   lambda_method(Closure , ControllerBase , Object[] ) +62
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +169
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
   System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
   System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
   System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
   System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +577
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +132
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163


来源: stackexchange

问:
What can you do in MSIL that you cannot do in C# or VB.NET?
All code written in .NET languages compiles to MSIL, but are there specific tasks / operations that you can do only using MSIL directly?

Let us also have things done easier in MSIL than C#, VB.NET, F#, j# or any other .NET language.

So far we have this:

Tail recursion

Generic Co/Contravariance (allowed in C# 4 and VB 10)

Overloads which differ only in return types

Override access modifiers

Have a class which cannot inherit from System.Object

Filtered exceptions (allowed in VB, and C# 6)

Calling a virtual method of the current static class type.

Get a handle on the boxed version of a value type.

Do a try/fault.

Usage of forbidden names.

Define your own parameterless constructors for value types.

Define events with a raise element.

Some conversions allowed by the CLR but not by C#.

Make a non main() method as the .entrypoint.

work with the native int and native unsigned int types directly.

Play with transient pointers

emitbyte directive in  MethodBodyItem

Throw and catch non System.Exception types

Inherit Enums (Unverified)

You can treat an array of bytes as a (4x smaller) array of ints.

You can have a field/method/property/event all have the same name(Unverified).

You can branch back into a try block from its own catch block.

You have access to the famandassem access specifier (protected internal is famorassem, but now allowed in C# 7.2 and VB 15.5)

Direct access to the <Module> class for defining global functions, or a module initializer.

Create and use non-zero-bound 1-based arrays

Create open-instance and closed-static delegates, and delegates of getters/setters

Swap two values without using a temp variable

Explicit interface implementation with any name, and implementing two interface functions in one (can be done in VB)

Declaring vtfixup (the equivalent of extern in C)

Specifying arbitrary modopt or modreq

答: I think the one I kept wishing for (with entirely the wrong reasons) was inheritance in Enums. It doesn't seem like a hard thing to do in SMIL (since Enums are just classes) but it's not something the C# syntax wants you to do.</p>

OwnerDisplayName: Binoj Antony

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Binoj Antony

OwnerDisplayName: scraimer

ContentLicense: CC BY-SA 2.5


问:
Static field initialization order (C#) - can someone explain this snippet?
I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.

I have come accross this statement/snipet on page 74:

Static field initializers run in the
  order in which the fields are
  declared. The following example
  illustrates this: X is initialized to
  0 and Y is initialized to 3.

```<code>class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}
</code>```

I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?

As an aside, coming from a C++ background, I tend to use the term ctor for constructor - however, I haven't yet come accross the term in C# - is the term ctor also used in the C# world?

[Edit]

A further example on the same page (in the book mentioned earlier) is this:

```<code>class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}
</code>```

The book states (for the example above):

The example prints 0 followed by 3
  because the field initializer that
  instantiates a Foo executes before X
  is initialized to 3:

I have some further questions w.r.t the examples.

Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor - atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the 'static' keyword. So I dont see how the examples relate to the section heading. What am I missing here?

In the second example, the (non static) ctor prints out the value of X - which had explicitly been assigned the value of 3 in the previous line - and yet, the output printed out is 0. Why?!

答:
In C#, primitive types such as int take on a default value.  For int, the default value is 0.  This is not like C++ where you have to initialize the value or it will be getting a random dirty value from memory.  Since Y is known to be of type int, X can be assigned it's default value of 0.

As far as the keyword ctor, I don't see it used very much as a C# programmer, but I am familiar with the term.  I believe it is used in a few places in Visual Studio, for instance in the object browser.

ContentLicense: CC BY-SA 3.0

Body:
I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.

I have come accross this statement/snipet on page 74:

Static field initializers run in the
  order in which the fields are
  declared. The following example
  illustrates this: X is initialized to
  0 and Y is initialized to 3.

class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}

I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?

As an aside, coming from a C++ background, I tend to use the term ctor for constructor - however, I haven't yet come accross the term in C# - is the term ctor also used in the C# world?

[Edit]

A further example on the same page (in the book mentioned earlier) is this:

class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}

The book states (for the example above):

The example prints 0 followed by 3
  because the field initializer that
  instantiates a Foo executes before X
  is initialized to 3:

I have some further questions w.r.t the examples.

Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor - atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the 'static' keyword. So I dont see how the examples relate to the section heading. What am I missing here?

In the second example, the (non static) ctor prints out the value of X - which had explicitly been assigned the value of 3 in the previous line - and yet, the output printed out is 0. Why?!


问:
Pressing button causes page to reload rather than run nessasary code?
I have a settings page in my website, the user edits his profile and then hits the update button which when properly working, like on chrome browser, will run certain code in the updateProfileData function. However in the firefox browser the page reloads as soon as I press the update button.

How can I prevent this and instead have the code I want run just like in chrome browser?

$('#update').on('click', event => {
  updateProfileData();
})

function updateProfileData() {
  //none of this will run because the page will instead reload
}

function pickFile() {
  fileButton.click()
}

function pickFile2() {
  fileButton2.click()
}

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  /* bottom: 0px;
  top: 0px; */
  width: 100%;
  height: 100%;
  margin:0px;

  font: Arial;
  font-family: sans-serif;
  font-weight:medium;

  text-align: center;

  /* bellow is to prevent all highlighting on the website. */
  -webkit-user-select: none; /* Chrome/Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+ */
}

/* #mp3Picker {
  color: grey;
} */

/* .middleSignUpDiv .container input {
  background-color: #F5F3F4;
  color: black;

  display: block;
  width: 390px;
  height: 125px;

  margin-left: auto;
  margin-right: auto;
  margin-top: 27px;
  margin-bottom: 17px;

  border-radius: 21px;
  border: none;

  padding-left: 15px;
  font-size: 0.95em;
  outline:none;

  border: solid transparent 2px;
} */

.justify {
  /* background-color: lightblue; */
  margin-top: 5px;
  display: flex;
  justify-content: center;
}

.soundscapeCaption:focus {
  border: solid #E2E2E2 2px;
}

.soundscapeCaption {
  /* margin-left: auto;
  margin-right: auto; */

  display: block;
  margin: 1px;
  padding: 1px;
  padding-left: 20px;
  padding-top: 20px;
  width: 390px;
  height: 115px;
  resize: none;
  background-color: #F5F3F4;
  border-radius: 21px;
  outline: none;
  font-size: 15px;
  border: solid transparent 2px;
}

.imgcontainer {
  display: block;
  position: relative;
  text-align: center;
}

input[type=file] {
  display:none;
}

.imgcontainer img {
  /* display: block; */
  /* vertical-align: middle; */
  object-fit: cover;
}

.middleSignUpDiv input:focus{
  border: solid #E2E2E2 2px;
  /* background-color: #B6B5B5; */
}

.middleSignUpDiv ::placeholder {
  font: Arial;
  font-family: sans-serif;
  /* font-size: 15px; */
  font-weight:medium;
  color: #B6B5B5;
}

/* input[type=text] {
  background-color: #F5F3F4;
  color: #B6B5B5;
} */

button {
  width: 215px;
  height: 55px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 25px;

  font: Arial;
  font-family: sans-serif;
  font-size: 19px;
  font-weight:600;
  color: white;
  background-color: #4152F1;
  border-radius: 7px;
  border: none;
  outline:none;
  cursor: pointer;
}

button:active{
background: blue;
}
button:visited {
   color: #4152F1;
}

/* .disclaimer {
  font: Arial;
  font-family: sans-serif;
  font-size: 12px;
  font-weight:medium;
  color: #CECECE;
  width: 390px;
  margin-left: auto;
  margin-right: auto;
}

.disclaimer em {
  color: #B4B4B4;
  cursor: pointer;
  font: Arial;
  font-family: sans-serif;
  font-size: 12px;
  font-weight:medium;
  font-style: normal
} */

/* Sign Up side */
/* body {
  top: 0px;
  bottom: 0px;

  float:left;
  display:inline-block;
  width: 100%;
  height: 100%;
  background-color: white;
  text-align: center;
} */

.descriptDiv {
  width: 100%;
  text-align: center;
  /* background-color: lightblue; */
}

.topSignUpDiv h1 {
  font: Arial;
  font-family: sans-serif;
  font-size: 40px;
  font-weight:600;
  /* text-align: center; */
  margin-top: 25px;
  margin-bottom: 0px;
}
/* .topSignUpDiv h3 {
  font: Arial;
  font-family: sans-serif;
  font-size: 19px;
  font-weight:400;
  color: white;
  background-color: #4152F1;
  border-radius: 7px;
  padding-top: 10px;
  padding-bottom: 10px;
  margin-top: 10px;
  width: 355px;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 55px;
} */

.disclaimer {
  margin-top: 50px;
  color: grey;
  font: Arial;
  font-family: sans-serif;
  font-size: 15px;
  font-weight:400;
  cursor: pointer;
}

#signout {
  font-weight: 500;
  color: grey;
  margin-top: 30px;
  cursor: pointer;
}

.cancelBtn {
  text-align: center;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  width: 100px;
  /* height: 50px; */
  font: Arial;
  font-family: sans-serif;
  font-size: 20px;
  font-weight:400;
  color: grey;
  cursor: pointer;
  border-radius: 5px;
}

/* .cancelBtn:hover {
} */

.cancelBtn:hover{
  background: #4152F1;
  color: white;
}

.profImg {
  margin-top: 20px;
  height: 150px;
  width: 150px;
  border-radius: 75px;
  border: solid #EFEFEF 1px;
  background-color: #EFEFEF;
  cursor: pointer;
}

.profImg:hover {
  border: solid #4152F1 1.2px;
}

.avatar {
  margin-top: 30px;
  height: 250px;
  width: 65%;
  border-radius: 20px;
  border: solid #EFEFEF 1px;
  background-color: #EFEFEF;
  cursor: pointer;
}

.avatar:hover {
  border: solid #4152F1 1.2px;
}</code>```

Edit profile/Settings

          <input type="file" id="fileButton" value="upload"/>

          <input type="file" id="fileButton2" value="upload"/>

            <textarea placeholder="Bio" class="soundscapeCaption" id="soundscapeCaption" rows="20" cols="50"></textarea>

          <button id="update">Update</button>

        Cancel

Sign out

```

答:
event.preventDefault() should solve your problem. So your code should look like:

```<code>$('#update').on('click', event => {
  // prevent default event
  event.preventDefault();
  updateProfileData();
})

function updateProfileData() {
  //none of this will run because the page will instead reload
}

function pickFile() {
  fileButton.click()
}

function pickFile2() {
  fileButton2.click()
}

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}
</code>```

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

Body:
I have a settings page in my website, the user edits his profile and then hits the update button which when properly working, like on chrome browser, will run certain code in the updateProfileData function. However in the firefox browser the page reloads as soon as I press the update button.

How can I prevent this and instead have the code I want run just like in chrome browser?

$('#update').on('click', event => {
  updateProfileData();
})

function updateProfileData() {
  //none of this will run because the page will instead reload
}

function pickFile() {
  fileButton.click()
}

function pickFile2() {
  fileButton2.click()
}

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}

html, body {
  /* bottom: 0px;
  top: 0px; */
  width: 100%;
  height: 100%;
  margin:0px;

  font: Arial;
  font-family: sans-serif;
  font-weight:medium;

  text-align: center;

  /* bellow is to prevent all highlighting on the website. */
  -webkit-user-select: none; /* Chrome/Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+ */
}

/* #mp3Picker {
  color: grey;
} */

/* .middleSignUpDiv .container input {
  background-color: #F5F3F4;
  color: black;

  display: block;
  width: 390px;
  height: 125px;

  margin-left: auto;
  margin-right: auto;
  margin-top: 27px;
  margin-bottom: 17px;

  border-radius: 21px;
  border: none;

  padding-left: 15px;
  font-size: 0.95em;
  outline:none;

  border: solid transparent 2px;
} */

.justify {
  /* background-color: lightblue; */
  margin-top: 5px;
  display: flex;
  justify-content: center;
}

.soundscapeCaption:focus {
  border: solid #E2E2E2 2px;
}

.soundscapeCaption {
  /* margin-left: auto;
  margin-right: auto; */

  display: block;
  margin: 1px;
  padding: 1px;
  padding-left: 20px;
  padding-top: 20px;
  width: 390px;
  height: 115px;
  resize: none;
  background-color: #F5F3F4;
  border-radius: 21px;
  outline: none;
  font-size: 15px;
  border: solid transparent 2px;
}

.imgcontainer {
  display: block;
  position: relative;
  text-align: center;
}

input[type=file] {
  display:none;
}

.imgcontainer img {
  /* display: block; */
  /* vertical-align: middle; */
  object-fit: cover;
}

.middleSignUpDiv input:focus{
  border: solid #E2E2E2 2px;
  /* background-color: #B6B5B5; */
}

.middleSignUpDiv ::placeholder {
  font: Arial;
  font-family: sans-serif;
  /* font-size: 15px; */
  font-weight:medium;
  color: #B6B5B5;
}

/* input[type=text] {
  background-color: #F5F3F4;
  color: #B6B5B5;
} */

button {
  width: 215px;
  height: 55px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 25px;

  font: Arial;
  font-family: sans-serif;
  font-size: 19px;
  font-weight:600;
  color: white;
  background-color: #4152F1;
  border-radius: 7px;
  border: none;
  outline:none;
  cursor: pointer;
}

button:active{
background: blue;
}
button:visited {
   color: #4152F1;
}

/* .disclaimer {
  font: Arial;
  font-family: sans-serif;
  font-size: 12px;
  font-weight:medium;
  color: #CECECE;
  width: 390px;
  margin-left: auto;
  margin-right: auto;
}

.disclaimer em {
  color: #B4B4B4;
  cursor: pointer;
  font: Arial;
  font-family: sans-serif;
  font-size: 12px;
  font-weight:medium;
  font-style: normal
} */

/* Sign Up side */
/* body {
  top: 0px;
  bottom: 0px;

  float:left;
  display:inline-block;
  width: 100%;
  height: 100%;
  background-color: white;
  text-align: center;
} */

.descriptDiv {
  width: 100%;
  text-align: center;
  /* background-color: lightblue; */
}

.topSignUpDiv h1 {
  font: Arial;
  font-family: sans-serif;
  font-size: 40px;
  font-weight:600;
  /* text-align: center; */
  margin-top: 25px;
  margin-bottom: 0px;
}
/* .topSignUpDiv h3 {
  font: Arial;
  font-family: sans-serif;
  font-size: 19px;
  font-weight:400;
  color: white;
  background-color: #4152F1;
  border-radius: 7px;
  padding-top: 10px;
  padding-bottom: 10px;
  margin-top: 10px;
  width: 355px;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 55px;
} */

.disclaimer {
  margin-top: 50px;
  color: grey;
  font: Arial;
  font-family: sans-serif;
  font-size: 15px;
  font-weight:400;
  cursor: pointer;
}

#signout {
  font-weight: 500;
  color: grey;
  margin-top: 30px;
  cursor: pointer;
}

.cancelBtn {
  text-align: center;
  margin-top: 20px;
  margin-left: auto;
  margin-right: auto;
  width: 100px;
  /* height: 50px; */
  font: Arial;
  font-family: sans-serif;
  font-size: 20px;
  font-weight:400;
  color: grey;
  cursor: pointer;
  border-radius: 5px;
}

/* .cancelBtn:hover {
} */

.cancelBtn:hover{
  background: #4152F1;
  color: white;
}

.profImg {
  margin-top: 20px;
  height: 150px;
  width: 150px;
  border-radius: 75px;
  border: solid #EFEFEF 1px;
  background-color: #EFEFEF;
  cursor: pointer;
}

.profImg:hover {
  border: solid #4152F1 1.2px;
}

.avatar {
  margin-top: 30px;
  height: 250px;
  width: 65%;
  border-radius: 20px;
  border: solid #EFEFEF 1px;
  background-color: #EFEFEF;
  cursor: pointer;
}

.avatar:hover {
  border: solid #4152F1 1.2px;
}

Edit profile/Settings

          <input type="file" id="fileButton" value="upload"/>

          <input type="file" id="fileButton2" value="upload"/>

            <textarea placeholder="Bio" class="soundscapeCaption" id="soundscapeCaption" rows="20" cols="50"></textarea>

          <button id="update">Update</button>

        Cancel

Sign out

Body:
event.preventDefault() should solve your problem. So your code should look like:

$('#update').on('click', event => {
  // prevent default event
  event.preventDefault();
  updateProfileData();
})

function updateProfileData() {
  //none of this will run because the page will instead reload
}

function pickFile() {
  fileButton.click()
}

function pickFile2() {
  fileButton2.click()
}

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.


问:
Create a user on AWS Workspaces with API
When creating a Workspace, I can create one or more users providing email and other information.

I am trying to do the same using AWS API or boto3 in python. None of WorkSpaces and DirectoryService in boto3 provide a way to create a user in AWS Simple AD.

How do I create a user on AWS Simple AD programmatically?

答:
Actually, it looks like you might be able to do this.  Check out the API documentation for workdocs.  It says "Creates a user in a Simple AD or Microsoft AD directory."

https://docs.aws.amazon.com/workdocs/latest/APIReference/API_CreateUser.html

```<code>POST /api/v1/users HTTP/1.1
Authentication: AuthenticationToken
Content-type: application/json

{
   "EmailAddress": "string",
   "GivenName": "string",
   "OrganizationId": "string",
   "Password": "string",
   "StorageRule": {
      "StorageAllocatedInBytes": number,
      "StorageType": "string"
   },
   "Surname": "string",
   "TimeZoneId": "string",
   "Username": "string"
}
</code>```

boto3 doc:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/workdocs.html#WorkDocs.Client.create_user

Body:
Actually, it looks like you might be able to do this.  Check out the API documentation for workdocs.  It says "Creates a user in a Simple AD or Microsoft AD directory."

https://docs.aws.amazon.com/workdocs/latest/APIReference/API_CreateUser.html

POST /api/v1/users HTTP/1.1
Authentication: AuthenticationToken
Content-type: application/json

{
   "EmailAddress": "string",
   "GivenName": "string",
   "OrganizationId": "string",
   "Password": "string",
   "StorageRule": {
      "StorageAllocatedInBytes": number,
      "StorageType": "string"
   },
   "Surname": "string",
   "TimeZoneId": "string",
   "Username": "string"
}

boto3 doc:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/workdocs.html#WorkDocs.Client.create_user


问:
How to remove space between bootstrap 4 column
how to remove spacing between bootstrap   columns ? bellow i have three bootstrap columns but whenever i try to remove space between them  it is not working as it was expected

<!doctype html>

   <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">

      <link href="phcoding.css" type="text/css" rel="stylesheet">
          <title>delinahproducts</title>

                lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

                lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

                lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

   ```

答:
Bootstrap's grid system is based on 12 columns, so change your col-md-3 to col-md-4. Then if you need to remove the gap between the columns, add no-gutters to your row like:

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">

        lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

        lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

        lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

```

Body:
Bootstrap's grid system is based on 12 columns, so change your col-md-3 to col-md-4. Then if you need to remove the gap between the columns, add no-gutters to your row like:

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">
<!--jquery easing plugin-->
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<!--custom css---->

<div class="container">
  <div class="row no-gutters">
    <div class="col-md-4">
      <div class="card">
        lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
      </div>
    </div>
    <div class="col-md-4">
      <div class="card">
        lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
      </div>
    </div>
    <div class="col-md-4">
      <div class="card">
        lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
      </div>
    </div>
  </div>
</div>


问:
Catch a UIImageView from a different .XIB
Dudes from this holy sanctuary,

New problem! I need to get the UIImageView from a different .XIB.
Let me put it in code so it get's simpler:

1)

```<code>-(UIImage *)grabScreenImage{

    //screen = IBOutlet for the UIImageView

    UIGraphicsBeginImageContext(self.screen.frame.size);
    [(CALayer *)self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"PASSED BY THE PHOTO DUDES");
    return image;

}
</code>```

2)

```<code>-(UIImage *)takeGraphScreenImage{

//shouldBeGraphViewController = IBOutlet for the other UIViewController
//shouldBeGraph = IBOutLet for the UIImageView in the ShouldBeGraphViewController

        UIGraphicsBeginImageContext(shouldBeGraphViewController.shouldBeTheGraph.frame.size);
        [(CALayer *)shouldBeGraphViewController.shouldBeTheGraph.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsGetCurrentContext();
        return image;
    }
</code>```

(1) works just fine, i capture the image and send it to by email but (2) doesn't.

i just copied and pasted and changed some parameters so it could be used by the other but it gives me loads of errors.

3) -(IBAction)sendMail{

```<code>MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc]init];

UIImage *curretScreen = [[self takeGrabScreenImage]retain];
UIImage *graphScreen = [[self takeGraphScreenImage]retain];

if ([MFMailComposeViewController canSendMail]){
    NSLog(@"ENTERED THE GOOD PART OF THE IF");
    mailComposer.mailComposeDelegate = self;
    [mailComposer setSubject:@"MY SCREENSHOT TEST"];
    [mailComposer addAttachmentData:UIImagePNGRepresentation(curretScreen) mimeType:@"image/png" fileName:@"SCREENSHOT"];
    [mailComposer addAttachmentData:UIImagePNGRepresentation(graphScreen) mimeType:@"image/png" fileName:@"SCREENSHOT-02"];

    //NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //NSString* documentsDirectory = [paths objectAtIndex:0];

    /*for (NSString *x in [self.photoLocations allKeys]){
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:x];
        UIImage *item = [UIImage imageWithContentsOfFile:fullPath];
        [mailComposer addAttachmentData:UIImagePNGRepresentation(item, 0.5) mimeType:@"image/jpeg" fileName:
    }*/

} else { ... }

[mailComposer setMessageBody:@"PUT YOUR MESSAGE HERE" isHTML:NO];
[self presentModalViewController:mailComposer animated:YES];
[mailComposer release];
[curretScreen release];
</code>```

}

I just need to take screenshots from both UIImageViews (from the two UIViewControllers) and send them by email, the email part is done and taking the first screenshot too, but take the second screenshot doesn't.  Gives me erros like these:

```<code>Mon May 16 21:02:46 FGringo EmailSending[1036] <Error>: CGContextSaveGState: invalid context 0x0
Mon May 16 21:02:46 FGringo EmailSending[1036] <Error>: CGContextSetAlpha: invalid context 0x0
</code>```

Help me, Please! (:

答:
```<code>- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // Dismiss image picker modal.
    [picker dismissModalViewControllerAnimated:YES];

    if ([MFMailComposeViewController canSendMail]) {
        // Create a string with HTML formatting for the email body.
        NSMutableString *emailBody = [[NSMutableString alloc] initWithString:@"<html><body>"];

        // Add some text to it.
        [emailBody appendString:@"<p>Body text goes here.</p>"];

        // You could repeat here with more text or images, otherwise
        // close the HTML formatting.
        [emailBody appendString:@"</body></html>"];
        NSLog(@"%@", emailBody);

        // Create the mail composer window.
        MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
        emailDialog.mailComposeDelegate = self;

        // Image to insert.
        UIImage *emailImage = [info objectForKey:UIImagePickerControllerOriginalImage];

        if (emailImage != nil) {
            NSData *data = UIImagePNGRepresentation(emailImage);
            [emailDialog addAttachmentData:data mimeType:@"image/png" fileName:@"filename_goes_here.png"];
        }

        [emailDialog setSubject:@"Subject goes here."];
        [emailDialog setMessageBody:emailBody isHTML:YES];

        [self presentModalViewController:emailDialog animated:YES];
        [emailDialog release];
        [emailBody release];
    }
}
</code>```

Body:
Dudes from this holy sanctuary,

New problem! I need to get the UIImageView from a different .XIB.
Let me put it in code so it get's simpler:

1)

-(UIImage *)grabScreenImage{

    //screen = IBOutlet for the UIImageView

    UIGraphicsBeginImageContext(self.screen.frame.size);
    [(CALayer *)self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"PASSED BY THE PHOTO DUDES");
    return image;

}

2)

-(UIImage *)takeGraphScreenImage{

//shouldBeGraphViewController = IBOutlet for the other UIViewController
//shouldBeGraph = IBOutLet for the UIImageView in the ShouldBeGraphViewController

        UIGraphicsBeginImageContext(shouldBeGraphViewController.shouldBeTheGraph.frame.size);
        [(CALayer *)shouldBeGraphViewController.shouldBeTheGraph.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsGetCurrentContext();
        return image;
    }

(1) works just fine, i capture the image and send it to by email but (2) doesn't.

i just copied and pasted and changed some parameters so it could be used by the other but it gives me loads of errors.

3) -(IBAction)sendMail{

MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc]init];

UIImage *curretScreen = [[self takeGrabScreenImage]retain];
UIImage *graphScreen = [[self takeGraphScreenImage]retain];

if ([MFMailComposeViewController canSendMail]){
    NSLog(@"ENTERED THE GOOD PART OF THE IF");
    mailComposer.mailComposeDelegate = self;
    [mailComposer setSubject:@"MY SCREENSHOT TEST"];
    [mailComposer addAttachmentData:UIImagePNGRepresentation(curretScreen) mimeType:@"image/png" fileName:@"SCREENSHOT"];
    [mailComposer addAttachmentData:UIImagePNGRepresentation(graphScreen) mimeType:@"image/png" fileName:@"SCREENSHOT-02"];

    //NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //NSString* documentsDirectory = [paths objectAtIndex:0];

    /*for (NSString *x in [self.photoLocations allKeys]){
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:x];
        UIImage *item = [UIImage imageWithContentsOfFile:fullPath];
        [mailComposer addAttachmentData:UIImagePNGRepresentation(item, 0.5) mimeType:@"image/jpeg" fileName:
    }*/

} else { ... }

[mailComposer setMessageBody:@"PUT YOUR MESSAGE HERE" isHTML:NO];
[self presentModalViewController:mailComposer animated:YES];
[mailComposer release];
[curretScreen release];

}

I just need to take screenshots from both UIImageViews (from the two UIViewControllers) and send them by email, the email part is done and taking the first screenshot too, but take the second screenshot doesn't.  Gives me erros like these:

Mon May 16 21:02:46 FGringo EmailSending[1036] <Error>: CGContextSaveGState: invalid context 0x0
Mon May 16 21:02:46 FGringo EmailSending[1036] <Error>: CGContextSetAlpha: invalid context 0x0

Help me, Please! (:


问:
HIbernate ignore fetching data from OnetoMany field
I would like to ignore @OnetoMany field in my entity. fetch data need to get actual fields but don't want to fire query to dependent table. But deleting data from parent table needs deletion from dependent table

I have tried @Transient that ignores but the delete is also being ignored. Is there any other option to tell JPA not to fetch data from childs table when i call the parent entity?

```<code>@Entity
Table(name = "User")
public class UserEntity implements Serializable {
    @Id
    @Column(name = "id")
    private int id;

    @Column(name = "SERIAL", unique = true, nullable = false)
    private String serial;

    @OneToMany(mappedBy = "serialBySerialId", cascade = CascadeType.ALL)
    private Set<UserActionEntity> userActionsById;

}

@Table(name = "user_action")
public class UserActionEntity implements Serializable {

    @Id
    @Column(name = "id")
    private int id;

    @Column(name = "action")
    private String action;

    @ManyToOne
    @JoinColumn(name = "USER_ID", referencedColumnName = "ID", nullable = false)
    private UserEntity userByUserId;

</code>```

答:
If you don't want to fire query to dependent table, you can use (fetch = FetchType.LAZY) on UserActionEntity property.</p>

```<code> @OneToMany(mappedBy = "serialBySerialId", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
        private Set<UserActionEntity> userActionsById;
</code>```

Body:
I would like to ignore @OnetoMany field in my entity. fetch data need to get actual fields but don't want to fire query to dependent table. But deleting data from parent table needs deletion from dependent table

I have tried @Transient that ignores but the delete is also being ignored. Is there any other option to tell JPA not to fetch data from childs table when i call the parent entity?

@Entity
Table(name = "User")
public class UserEntity implements Serializable {
    @Id
    @Column(name = "id")
    private int id;

    @Column(name = "SERIAL", unique = true, nullable = false)
    private String serial;

    @OneToMany(mappedBy = "serialBySerialId", cascade = CascadeType.ALL)
    private Set<UserActionEntity> userActionsById;

}

@Table(name = "user_action")
public class UserActionEntity implements Serializable {

    @Id
    @Column(name = "id")
    private int id;

    @Column(name = "action")
    private String action;

    @ManyToOne
    @JoinColumn(name = "USER_ID", referencedColumnName = "ID", nullable = false)
    private UserEntity userByUserId;

Body:
If you don't want to fire query to dependent table, you can use (fetch = FetchType.LAZY) on UserActionEntity property.

 @OneToMany(mappedBy = "serialBySerialId", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
        private Set<UserActionEntity> userActionsById;