Tuesday, September 26, 2017

ASP.net MVC Razor view on Mono Mac

Leave a Comment

I created an ASP.net MVC application using Visual Studio Community Edition for Mac. When I ran the default HomeController and Index view work fine. Then I made a BookController and inside views added a folder Book and Index.cshtml file. However I keep getting the following error:

System.InvalidOperationException The view found at '~/Views/book/Index.cshtml' was not created.

Description:

HTTP 500.Error processing request.

Details:

Non-web exception. Exception origin (name of application or object): System.Web.Mvc. Exception stack trace: at System.Web.Mvc.BuildManagerCompiledView.Render (System.Web.Mvc.ViewContext viewContext, System.IO.TextWriter writer) [0x00061] in :0 at System.Web.Mvc.ViewResultBase.ExecuteResult (System.Web.Mvc.ControllerContext context) [0x00080] in :0 at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult (System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x00000] in :0 at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive (System.Collections.Generic.IList1[T] filters, System.Int32 filterIndex, System.Web.Mvc.ResultExecutingContext preContext, System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x0000b] in <cc73190bab9d435c831510ff295c572a>:0 at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive (System.Collections.Generic.IList1[T] filters, System.Int32 filterIndex, System.Web.Mvc.ResultExecutingContext preContext, System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x0009b] in :0 at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters (System.Web.Mvc.ControllerContext controllerContext, System.Collections.Generic.IList1[T] filters, System.Web.Mvc.ActionResult actionResult) [0x0000a] in <cc73190bab9d435c831510ff295c572a>:0 at System.Web.Mvc.Async.AsyncControllerActionInvoker+<>c__DisplayClass21+<>c__DisplayClass2b.<BeginInvokeAction>b__1c () [0x0008a] in <cc73190bab9d435c831510ff295c572a>:0 at System.Web.Mvc.Async.AsyncControllerActionInvoker+<>c__DisplayClass21.<BeginInvokeAction>b__1e (System.IAsyncResult asyncResult) [0x00041] in <cc73190bab9d435c831510ff295c572a>:0 at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResult1[TResult].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in :0 at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase1[TResult].End () [0x00029] in <cc73190bab9d435c831510ff295c572a>:0 at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in <cc73190bab9d435c831510ff295c572a>:0 at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0 at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d (System.IAsyncResult asyncResult, System.Web.Mvc.Controller+ExecuteCoreState innerState) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0 at (wrapper delegate-invoke) System.Web.Mvc.Async.EndInvokeVoidDelegate1[System.Web.Mvc.Controller+ExecuteCoreState]:invoke_void_IAsyncResult_TState (System.IAsyncResult,System.Web.Mvc.Controller/ExecuteCoreState) at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncVoid1[TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0 at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase1[TResult].End () [0x00029] in :0 at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in :0 at System.Web.Mvc.Async.AsyncResultWrapper.End (System.IAsyncResult asyncResult, System.Object tag) [0x00000] in :0 at System.Web.Mvc.Controller.EndExecuteCore (System.IAsyncResult asyncResult) [0x00000] in :0 at System.Web.Mvc.Controller.b__15 (System.IAsyncResult asyncResult, System.Web.Mvc.Controller controller) [0x00000] in :0 at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncVoid1[TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in <cc73190bab9d435c831510ff295c572a>:0 at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase1[TResult].End () [0x00029] in :0 at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in :0 at System.Web.Mvc.Async.AsyncResultWrapper.End (System.IAsyncResult asyncResult, System.Object tag) [0x00000] in :0 at System.Web.Mvc.Controller.EndExecute (System.IAsyncResult asyncResult) [0x00000] in :0 at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute (System.IAsyncResult asyncResult) [0x00000] in :0 at System.Web.Mvc.MvcHandler.b__5 (System.IAsyncResult asyncResult, System.Web.Mvc.MvcHandler+ProcessRequestState innerState) [0x00000] in :0 at (wrapper delegate-invoke) System.Web.Mvc.Async.EndInvokeVoidDelegate1[System.Web.Mvc.MvcHandler+ProcessRequestState]:invoke_void_IAsyncResult_TState (System.IAsyncResult,System.Web.Mvc.MvcHandler/ProcessRequestState)
at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncVoid
1[TState].CallEndDelegate (System.IAsyncResult asyncResult) [0x00000] in :0 at System.Web.Mvc.Async.AsyncResultWrapper+WrappedAsyncResultBase`1[TResult].End () [0x00029] in :0 at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult] (System.IAsyncResult asyncResult, System.Object tag) [0x00007] in :0 at System.Web.Mvc.Async.AsyncResultWrapper.End (System.IAsyncResult asyncResult, System.Object tag) [0x00000] in :0 at System.Web.Mvc.MvcHandler.EndProcessRequest (System.IAsyncResult asyncResult) [0x00000] in :0 at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest (System.IAsyncResult result) [0x00000] in :0 at System.Web.HttpApplication.async_handler_complete_cb (System.IAsyncResult ar) [0x00015] in /private/tmp/source-mono-2017-02/bockbuild-2017-02/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class

I Googled around and people said I have to make sure the web.config inside views folder is as follows:

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> 

That is it matches the version of system.web.mvc and looking inside system.web.mvc the version is:

5.2.3

And the default view in HomeController works. I am trying out ASP.net MVC on Mac first time and never had this type of problem on Windows.

Any help is welcome.

Update Controller code:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using TestMvcFromMac.Models;  namespace TestMvcFromMac.Controllers {  public class BookController : Controller  {      //Category category = new Category();       public ActionResult Index()     {         return View ();     }    } } 

2 Answers

Answers 1

I am guessing that the problem might happen because you are creating all the stuff manually and not letting template engine generate something for you like in visual studio in windows (Personally did not try Mac version so I dont know exactly how it looks like). Anyway lets suppose you have created your controller and then Book folder. But there is something to configure manually as well if its not configured, and that is routing for current controller.

You have to set routing logic in RouteConfig file class, so you would have something like this:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");          routes.MapRoute(             name: "Default",             url: "{controller}/{action}/{id}",             defaults: new { controller = "Book" , action = "Index", id = UrlParameter.Optional }         ); 

Refere to this question for more details here.

Another version I guess is setting the view name inside return statement itself like this:

return View("Index") 

If this is not the case please let me know so I can see any other alternative for this problem...

Answers 2

medium Visual Studio for Mac 2017 MVC version 5.3.2

I had the exact same problem. My Index views was working and other actions was not, giving the same error. I don't know why but when I add a route attribute manually in the beginning of the action in the controller, it was the solutions for my case

steps 1) add following line to the routeconfig.cs file

 routes.MapMvcAttributeRoutes(); 

2) add route attribute to the action manually like

  [Route("ViewName/ActionName/")]     public ActionResult ActionName()     {....   return View(the_model);    } 
Read More

JavaScript - Get HTML of current line in contentEditable div

Leave a Comment

I have got my contentEditable div:

div {    width: 200px;    height: 300px;    border: 1px solid black;  }
<div contenteditable="true" spellcheck="false" style="font-family: Arial;">      <b>Lorem ipsum</b> dolor sit amet, <u>consectetur adipiscing elit.       Morbi sagittis</u> <s>mauris porta arcu auctor, vel aliquam ligula ornare.</s>       Sed at <span id="someId">semper neque, et dapibus metus.       Maecenas dignissim est non nunc feugiat</span>       sollicitudin. Morbi consequat euismod consectetur. Mauris orci       risus, <b>porta quis erat ac, malesuada</b> fringilla odio.  </div>        <button>Get current line HTML</button>

And I want to create a button which gives me HTML code from the current line. For example:
When my caret is on the second line I want to get:

amet, <u>consectetur</u> 

or on seventh line:

<span id="someId">dapibus metus. Maecenas</span> 

I tried to do that using Rangy, but that didn't work. How can I do that using JavaScript and/or JQuery?
Thanks for help.

2 Answers

Answers 1

I will not code you the full finished code but here are good help that will get you the result.

First you need to get a method for figuring out lines. I suggest looking at the answer in this stackoverflow: How to select nth line of text (CSS/JS) From that you can get line number for a specific word.

What word your caret is on you can get from this information: How can I get the word that the caret is upon inside a contenteditable div?

Combining the line number functionality with current caret word you will be able to return a full row where your caret is.

Answers 2

This solution is based on the example proposed by Mozilla in Selection.modify(), but using lineboundary granularity and playing with move and extend alter parameters.

To preserve caret position, the range of the selection is stored/restored.

Play with the width of the content, edit the snippet and check it out.

You got your HTML.

function getSelectionHtml() {    var selection = window.document.selection,      range, oldBrowser = true;      if (!selection) {      selection = window.getSelection();      range = selection.getRangeAt(0);      oldBrowser = false;    } else      range = document.selection.createRange();      selection.modify("move", "backward", "lineboundary");    selection.modify("extend", "forward", "lineboundary");      if (oldBrowser) {      var html = document.selection.createRange().htmlText;      range.select();      return html;    }      var html = document.createElement("div");      for (var i = 0, len = selection.rangeCount; i < len; ++i) {      html.appendChild(selection.getRangeAt(i).cloneContents());    }      selection.removeAllRanges();    selection.addRange(range);    return html.innerHTML;  }    document.getElementById("content").onmouseup = function(e) {    var html = getSelectionHtml();    document.getElementById("text").innerHTML = html;    document.getElementById("code").textContent = html;  };
h4,  p {    margin: 0;  }    #code {    width: 100%;    min-height: 30px;  }    #content {    margin: 15px;    padding: 2px;    width: 200px;    height: 300px;    border: 1px solid black;  }
<textarea id="code"></textarea>  <div id="text"></div>    <div contenteditable="true" id="content" spellcheck="false" style="font-family: Arial;">    <b>Lorem ipsum</b> dolor sit amet, <u>consectetur adipiscing elit.       Morbi sagittis</u> <s>mauris porta arcu auctor, vel aliquam ligula ornare.</s> Sed at <span id="someId">semper neque, et dapibus metus.       Maecenas dignissim est non nunc feugiat</span> sollicitudin. Morbi consequat euismod consectetur. Mauris orci risus, <b>porta quis erat ac, malesuada</b> fringilla odio.  </div>

Read More

Annotate with django-graphene and filters

Leave a Comment

I would like to sum a field in my resolver of django-graphene using django-filter. Typically my resolvers would look like:

my_model = DjangoFilterConnectionField(         MyModelNode,         filterset_class=MyModelFilter)  def my_resolver(self, args, context, info):      return MyModelFilter(         data=format_query_args(args),         queryset=self).qs 

Which works fine.
However, I would like to provide a custom queryset to the model filter so that I can perform aggregations on fields. I'm trying to do something like this:

def my_resolver(self, args, context, info):     queryset = MyModel.objects.values(         'customer_id').annotate(         cost_amt=Sum('cost_amt', output_field=FloatField()))      return MyModelFilter(         data=format_query_args(args),         queryset=queryset).qs 

Inspecting the raw SQL in GraphiQL, it looks correct. However, the error message I receive from GraphQL is

"message": "Received incompatible instance \"{'cost_amt': 260.36, 'customer_id': 300968697}\"." 

This is the correct result, but I'm unsure why GraphQL is getting this object from django-graphene. How can I provide a custom queryset and make this work?

3 Answers

Answers 1

I assume that your problem occurs because .values() returns a dictionary rather than a model instance.

You can try to avoid the usage of .values() as you can see in the last two examples of the aggregation cheat sheet and in the Generate aggregates for each item in a QuerySet section:

def my_resolver(self, args, context, info):     queryset = MyModel.objects.annotate(         cost_amt=Sum('cost_amt', output_field=FloatField()))  return MyModelFilter(     data=format_query_args(args),     queryset=queryset).qs    

But keep in mind that you will have to adjust your "front-end"/receiver accordingly because now your resolver will return a queryset and not a dictionary.

Answers 2

For queryset to work you need to get instance of the model which you can get using

queryset = MyModel.objects.annotate(cost_amt=Sum('cost_amt', output_field=FloatField())) 

and then you can try further actions.

return MyModelFilter(data=format_query_args(args),queryset=queryset).qs 

still error

Try ASSET UNION and see if that works else you can also try DjangoConnectionField from relay.connection.

Answers 3

It looks like django-graphene is expecting a QuerySet of model instances, when you call .values() on a QuerySet you will get back a queryset of dictionaries, hence the Received incompatible instance.

You may be able to use subquery expressions, or do some rawsql queries both of which will return model instances, it really depends on the type of relationships you have setup on your models.

It almost looks like it may be easier to do this annotation from the other end of the relationship (customer side) as you wouldn't need the to use .values() but it may not work for what you need.

Read More

Loading SavedModel is a lot slower than loading a tf.train.Saver checkpoint

Leave a Comment

I changed from tf.train.Saver to the SavedModel format which surprisingly means loading my model from disk is a lot slower (instead of a couple of seconds it takes minutes). Why is this and what can I do to load the model faster?

I used to do this:

# Save model saver = tf.train.Saver() save_path = saver.save(session, model_path)  # Load model saver = tf.train.import_meta_graph(model_path + '.meta') saver.restore(session, model_path) 

But now I do this:

# Save model builder = tf.saved_model.builder.SavedModelBuilder(model_path) builder.add_meta_graph_and_variables(session, [tf.saved_model.tag_constants.TRAINING]) builder.save()  # Load model tf.saved_model.loader.load(session, [tf.saved_model.tag_constants.TRAINING], model_path) 

0 Answers

Read More

Java WSDL modify or hide certain properties on Web View

Leave a Comment

TLDR Is it possible to create an "alias" for the IP address (such as 0.0.0.0:8080/services as SERVER_1) or any other property on the WSDL content while someone's reading it? Similar to:

<entry key="org.apache.cxf.endpoint.private" value="true"/> 

For the services list, that keeps the functionality intact but hides the services list.

If yes, how? If not, is there a way to hide it without using @XmlTransient because if we used it, and from my understanding, the program wouldn't even map this element and thus no longer work.


I'm working with SOAP services using Spring and JAX-RS.

We're securing our apps, after an ethical hacking test, the results thrown that we were exposing services and production IP addresses on our URLs.

We were able to hide the services list from the web view, for example, if we access http://localhost:8080/foo/services we get this text:

No services have been found. 

Which is fine and we've done it by following this answer, but instead of being on cxf-servlet.xml file, it was on the applicationContext-{moduleName}.xml file.

Now, if we know, or have access to any of the WSDL paths, we can still see the WSDL contents (which includes production IP addresses), for example if we entered:

http://localhost:8080/foo/services/bar?_wsdl 

We have a similar definition as below (I edited it for security reasons):

<application     xmlns="http://wsdl.dev.java.net/2009/02"     xmlns:xs="http://www.w3.org/2001/XMLSchema">     <grammars/>     <resources base="http://localhost:8080/foo/services/bar">         <resource path="/VX">             <resource path="/anotherPath">                 <method name="POST">                     <request>                         <representation mediaType="application/x-www-form-urlencoded">                             <param name="someParam" style="query" type="xs:string"/>                         </representation>                     </request>                     <response>                         <representation mediaType="application/json">                             <param name="anotherParam" style="plain" type="xs:string"/>                         </representation>                     </response>                 </method>             </resource>         </resource>     </resources> </application> 

How could I, for example edit on run time the property

<resources base="http://localhost:8080/foo/services/bar"> 

To something like

<resources base="SERVER_1"> 

So, we internally know what IP address does SERVER_1 has, but people outside that manage to get there doesn't, in other words how could I create an alias for the IP address and use it instead of the real ip address on it?

This is because we have about 10 servers, each with a different IP address, and if we need to do some production debugging we need to know which server we're in, so we would like to avoid hiding the whole WSDL content (as I know it can be done, because a module has this configuration).

I know I can use @XmlTransient annotation, but as per docs:

Prevents the mapping of a JavaBean property/type to XML representation.

So, in my understanding, if I use this annotation over the property containing the IP address, then it would no longer be working.

If this isn't possible, which other suggestions would you have in order to make a workaround for this particular case?

We create the services with top-down approach (i.e. we're given the WSDL and we use wsdl2java to create Java Objects + service interface from it)

1 Answers

Answers 1

TLDR: Use DNS to assign names to your IP addresses.

We're securing our apps, after an ethical hacking test, the results thrown that we were exposing services and production IP addresses on our URLs

You have a SOAP-Service. To use it one needs to know the address of the endpoint. So you'll "expose" it no matter what. Security through obscurity is not recommended.

So, we internally know what IP address does SERVER_1 has, but people outside that manage to get there doesn't, in other words how could I create an alias for the IP address and use it instead of the real ip address on it?

That's what DNS was invented for. An "alias" for the IP address. It's bad practise to use IP-Addresses for services. So set up a DNS (or use host files) to assign a name per IP address.

Read More

Publish from Visual Studio and automatically encrypt appSettings using aspnet_regiis

Leave a Comment

I have web application that is deployed to my local IIS server under Sites\Default, it works fine and right now I want to make it more secure - I want to encrypt connection strings and appSettings.
Inside pubxml file I've added this line:

<MSDeployEnableWebConfigEncryptRule>true</MSDeployEnableWebConfigEncryptRule> 

but that only encrypts connections strings. I know that I can manually call:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -pe "appSettings" -site Default -app "/" 

on my server after deploy to encrypt external file containing appSettings, but I must do that manually.

My question is how can I deploy website from Visual Studio (Build > Publish) and have that aspnet_regiis command execute automatically after publish succeeded.

I found information that I could use runcommand and other about bat files, but I'm not calling MSDeploy from command line.
I've also found information that I should build custom provider and call it from MSDeploy.

How should I edit my pubxml file to get this behaviour?

EDIT1:
I've managed to hook After Deploy Target using:

<Target Name="EncryptAppSettings" AfterTargets="MSDeployPublish" >   <Message Text="Encrypting appSettings" />   <Exec Command="aspnet_regiis -pe &quot;appSettings&quot; -site Default -app &quot;/&quot;" />   <Message Text="AppPath: $(DeployIisAppPath)" /> </Target> 

But now I get this error:

The command "aspnet_regiis -pe "appSettings" -site Default -app "/"" exited with code 9009.

EDIT2:
I've tried using runCommand like this:

<ItemGroup>   <MsDeploySourceManifest Include="runCommand">     <path>aspnet_regiis -pe &quot;appSettings&quot; -site Default -app &quot;/&quot;</path>     <waitInterval>10000</waitInterval>     <AdditionalProviderSettings>waitInterval</AdditionalProviderSettings>   </MsDeploySourceManifest> </ItemGroup> 

but I had no luck. I found blog about postSync:runCommand, but I'd like to call that directly from VS so I'd like to add that to publish profile.

EDIT3:
I'm adding my publish profile below:

<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">   <PropertyGroup>     <WebPublishMethod>MSDeploy</WebPublishMethod>     <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>     <LastUsedPlatform>Any CPU</LastUsedPlatform>     <SiteUrlToLaunchAfterPublish />     <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>     <ExcludeApp_Data>False</ExcludeApp_Data>     <MSDeployServiceURL>192.168.5.50</MSDeployServiceURL>     <DeployIisAppPath>Default</DeployIisAppPath>     <RemoteSitePhysicalPath />     <SkipExtraFilesOnServer>False</SkipExtraFilesOnServer>     <MSDeployPublishMethod>WMSVC</MSDeployPublishMethod>     <EnableMSDeployBackup>True</EnableMSDeployBackup>     <MSDeployEnableWebConfigEncryptRule>True</MSDeployEnableWebConfigEncryptRule>     <UserName>LocalAdmin</UserName>     <_SavePWD>True</_SavePWD>     <PublishDatabaseSettings>       <Objects xmlns="">         <ObjectGroup Name="ApplicationDbContext" Order="1" Enabled="False">           <Destination Path="Data Source=192.168.5.51;Initial Catalog=GameBit;User ID=GUser;Password=MyRealPassword;Application Name=EntityFramework" Name="Data Source=192.168.5.51;Initial Catalog=GameBit;User ID=GUser;Password=MyRealPassword;MultipleActiveResultSets=True;Application Name=EntityFramework" />           <Object Type="DbCodeFirst">             <Source Path="DBContext" DbContext="Api.ApplicationDbContext, Api" Origin="Configuration" />           </Object>         </ObjectGroup>       </Objects>     </PublishDatabaseSettings>   </PropertyGroup>    <PropertyGroup>     <UseMsdeployExe>true</UseMsdeployExe>     <AllowUntrustedCertificate>True</AllowUntrustedCertificate>   </PropertyGroup>    <ItemGroup>     <MSDeployParameterValue Include="$(DeployParameterPrefix)ApplicationDbContext-Web.config Connection String">       <ParameterValue>metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=192.168.5.51;Initial Catalog=GameBit;User ID=GUser;Password=MyRealPassword;MultipleActiveResultSets=True;Application Name=EntityFramework"</ParameterValue>     </MSDeployParameterValue>   </ItemGroup>    <!--<ItemGroup>   <MsDeploySourceManifest Include="runCommand">     <Path>dir</Path>   </MsDeploySourceManifest> </ItemGroup>-->     <!--<Target Name="EncryptImportantSettings" AfterTargets="MSDeployPublish" >     <Message Text="Encrypting appSettings" />     --><!--<Exec Command="aspnet_regiis -pe &quot;appSettings&quot; -site Default -app &quot;/&quot;" />--><!--   <ItemGroup>     <MsDeploySourceManifest Include="runCommand">       <path>dir/b >> C:\temp\log.txt</path>       --><!--<waitInterval>10000</waitInterval>--><!--       --><!--<AdditionalProviderSettings>waitInterval</AdditionalProviderSettings>--><!--     </MsDeploySourceManifest>   </ItemGroup>   <Message Text="AppPath: $(DeployIisAppPath)" />   </Target>--> </Project> 

I've noticed that when I use MSDeploy I can see command that is executed during publish:

"C:\Program Files (x86)\IIS\Microsoft Web Deploy V3\msdeploy.exe" -source:manifest='D:\GameBit\API\obj\Release\Package\API.SourceManifest.xml' -dest:auto,ComputerName="https://192.168.5.50:8172/msdeploy.axd?site=Default",UserName='LocalAdmin',Password="MyRealPassword",IncludeAcls='False',AuthType='Basic' -verb:sync -enableRule:EncryptWebConfig -enableRule:EncryptWebConfig -disableLink:AppPoolExtension -disableLink:ContentExtension -disableLink:CertificateExtension -setParamFile:"D:\GameBit\API\obj\Release\Package\API.Publish.Parameters.xml" -allowUntrusted -retryAttempts=2 -userAgent="VS12.0:PublishDialog:WTE12.5.60612.0"

Can I add -postSync:runCommand="" to that command from publish profile? As I found on MS site this parameter allows to execute command on destination machine.

EDIT4:
I found information about Web Deploy Operation Settings and postSync setting, but I don't know where to set it, I don't want to edit Microsoft.Web.Publishing.targets from MSBuild folder

I need to execute command on remote machine after publish succeeded.

1 Answers

Answers 1

After going through your all edits and a bit of research from me , you want to execute the following command after the publish from the Visual Studio

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -pe "appSettings" -site Default -app "/"  

If i understood right , You can try wrapping the ItemGroup in a Target with AfterTargets set to AddIisSettingAndFileContentsToSourceManifest

<Target Name="executeinHosts" AfterTargets="AddIisSettingAndFileContentsToSourceManifest">     <ItemGroup>       <MsDeploySourceManifest Include="runCommand">          //here would be your path that need to run after the publish       </MsDeploySourceManifest>     </ItemGroup>   </Target> 

So in Your case this is how that part should look:

<Target Name="executeinHosts" AfterTargets="AddIisSettingAndFileContentsToSourceManifest">     <ItemGroup>       <MsDeploySourceManifest Include="runCommand">          <path>C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -pe "appSettings" -site $(DeployIisAppPath) -app "/"</path>       </MsDeploySourceManifest>     </ItemGroup>   </Target> 
Read More

in webpack, force some modules to be automatically loaded at startup

Leave a Comment

In my server-side bundle, I have some modules that contains server-side api and I would like to make these modules to be loaded (and run) as soon as possible (at the same time as the entry point).

I have some constraints:

  • I don't know the name of these modules (they are generated during the compilation and they are just "marked" from a loader, using this._module.meta.myApiModule = true).
    These modules are partially shared between client and server in an isomorphic web app. The client knows the server module hash because client-side and server-side module share the same hash (thanks to webpack.HashedModuleIdsPlugin). In some situations, the client make api calls to the server, and the module that holds the api must be loaded before the call.

  • all marked modules must be called (required) at startup.
    These modules contains code to register their api (eg. mainFramowork.registerRpcApi(...)) this is why they must be loaded at startup.

more details:

I use vuejs and my .vue files are processed by webpack. Each vue file generates webpack modules (for the script part, the markup part, style, and optionally customBlocks that can be used freely)

foo.vue (file) -> html (webpack module) -> script (webpack module) -> style (webpack module) -> customBlock (webpack module, rawRequest:"!!babel-loader!addmeta-loader?{"mark":"api"}!XXX/node_modules/vue-loader/lib/selector?type=customBlocks&index=1!./foo.vue")  bar.vue -> html (webpack module) -> script (webpack module) -> style (webpack module) -> customBlock (webpack module, rawRequest:"!!babel-loader!addmeta-loader?{"mark":"api"}!XXX/node_modules/vue-loader/lib/selector?type=customBlocks&index=1!./bar.vue") 

Now, my aim is to call ALL "customBlock modules":

  • at startup (how??)
  • on chunk load (maybe with an entry point in the chunk??, this implies to move all my customBlocks modules in a new chunk then dynamically create a module that will call all my customBlock modules (wow))
  • by hand: require('please_call_all_custom_blocks_modules_thanks')

2 Answers

Answers 1

I think what you want is something like this

// loader.js var moduleName = getSomeModuleNameInRuntime(); require("bundle!./path/" + moduleName)(function(myModule) {   // ... }); 

see this issue here

Answers 2

You can include them via webpack config directly.

//webpack.config.js  {   entry: {     "server" : [       'myrequiredBundle1',        'myrequiredBundleN',        './server.entry.js'     ]   } } 

otherwise:

// server.entry.js  import 'myRequiredBundle1'; import 'myRequiredBundleN';  /* the rest */ 

I would implement your feature using WebpackDLL and WebpackDLLReference. In this way you can perfectly control names and exports of your dll... Just make your isomorphic library a DLL.

You can also have a look at:

  1. library => https://webpack.js.org/configuration/output/#output-library
  2. webpack magic comments => https://webpack.js.org/api/module-methods/#import-
Read More