问:
Inline editing datatable jquery
Hi I have been trying to follow this tutorial about inline editing http://www.vandelaydesign.com/inline-edit-with-ajax/ . I want to apply it in my data table. When the user clicks the edit button the corresponding columns within its line becomes an input, but I do not know how to turn it that way. In the tutorial it uses .prev in jquery to get the value of the of the span but I do not know how to do that in my case. This is what my table looks like:

Category name and desc should become inputs when edit button is clicked. How do I do that?

```<code><tbody>
    <?php foreach ($categories as $category) { ?>
        <tr>
            <td> <span id="<?= $category->category_id ?>" class="datainfo"> <?= $category->category_name ?>  </span> </td>
            <td>
                <?= $category->category_desc ?>
            </td>
            <td>
                <?= $category->created_on ?>
            </td>
            <td>
                <?= $category->updated_on ?>
            </td>
            <td>
                <?= $category->status ?>
            </td>
            <td>
                <button type="button" name="edit_cat" class="btn btn-light btn-sm edit_cat">
                    <!-- data-id="<?= $category->category_id ?>" -->
                    <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                </button>
            </td>
        </tr>
        <?php } ?>
</tbody>
</code>```

Javascript:

```<code> $(document).on('click', '.edit_cat', function() {
      console.log('edit category');
      // console.log( $(this).data('id') );
      var dataset = $(this).prev(".datainfo");
      console.log(dataset);
      var theid   = dataset.attr("id");
      console.log(theid);
      var newid   = theid+"-form";
      var currval = dataset.text();

      dataset.empty();

       $('<input type="text" name="'+newid+'" id="'+newid+'" value="'+currval+'" class="hlite">').appendTo(dataset);

    });
</code>```

I also need help in future proofing after solving this problem, How would I go about saving it, maybe getting the span id and start from there?

答:
Datatables have a build in implementation of inline editing.

It gets installed as an own extension

Inline editing in Editor is activated through the use of the inline() API method. Simply call the method and pass in the cell you want to edit as the first parameter.

Take a closer look here - https://editor.datatables.net/examples/inline-editing/simple

Title: Inline editing datatable jquery

Body:
Hi I have been trying to follow this tutorial about inline editing http://www.vandelaydesign.com/inline-edit-with-ajax/ . I want to apply it in my data table. When the user clicks the edit button the corresponding columns within its line becomes an input, but I do not know how to turn it that way. In the tutorial it uses .prev in jquery to get the value of the of the span but I do not know how to do that in my case. This is what my table looks like:

Category name and desc should become inputs when edit button is clicked. How do I do that?

    <?php foreach ($categories as $category) { ?>

             <span id="<?= $category->category_id ?>" class="datainfo"> <?= $category->category_name ?>

                <?= $category->category_desc ?>

                <?= $category->created_on ?>

                <?= $category->updated_on ?>

                <?= $category->status ?>

                <button type="button" name="edit_cat" class="btn btn-light btn-sm edit_cat">

                </button>

        <?php } ?>

Javascript:

 $(document).on('click', '.edit_cat', function() {
      console.log('edit category');
      // console.log( $(this).data('id') );
      var dataset = $(this).prev(".datainfo");
      console.log(dataset);
      var theid   = dataset.attr("id");
      console.log(theid);
      var newid   = theid+"-form";
      var currval = dataset.text();

      dataset.empty();

       $('<input type="text" name="'+newid+'" id="'+newid+'" value="'+currval+'" class="hlite">').appendTo(dataset);

    });

I also need help in future proofing after solving this problem, How would I go about saving it, maybe getting the span id and start from there?


来源: stackexchange

问:
How to Get Groups of Files from GetFiles()
I have to process files everyday.  The files are named like so:

```<code> fg1a.mmddyyyy
 fg1b.mmddyyyy
 fg1c.mmddyyyy

 fg2a.mmddyyyy
 fg2b.mmddyyyy
 fg2c.mmddyyyy
 fg2d.mmddyyyy
</code>```

If the entire file group is there for a particular date, I can process it.  If it isn't there, I should not process it.  I may have several partial file groups that run over several days.  So when I have fg1a.12062017, fg1b.12062017 and fg1c.12062017, I can process that group (fg1) only.

Here is my code so far.  It doesn't work because I can't figure out how to get only the full groups to add to the the processing file list.

```<code>        fileList = Directory.GetFiles(@"c:\temp\");

        string[] fileGroup1 = { "FG1A", "FG1B", "FG1C" }; // THIS IS A FULL GROUP
        string[] fileGroup2 = { "FG2A", "FG2B", "FG2C", "FG2D" };

        List<string> fileDates = new List<string>();
        List<string> procFileList;

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        bool allFiles = true;
        foreach (string fg in fileGroup1)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }

                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }

            }

        }

        foreach (string fg in fileGroup2)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }
                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }
            }

        }
</code>```

Any help or advice would be greatly appreciated.

答:
With everyone's help, I solved it too.  This is what I'm going with because it's the most maintainable for me but the solutions were so smart!!!  Thanks everyone for your help.</p>

```<code>   private void CheckFiles()
    {
        var fileGroups = new[] {
          new [] { "FG1A", "FG1B", "FG1C", "FG1D" },
          new[] { "FG2A", "FG2B", "FG2C", "FG2D", "FG2E" } };

        List<string> fileDates = new List<string>();
        List<string> pfiles = new List<string>();

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        // check if a date has all the files
        foreach (string fd in fileDates)
        {
            int fgCount = 0;
            // for each file group
            foreach (Array masterfg in fileGroups)
            {
                foreach (string fg in masterfg)
                {
                    // see if all the files are there
                    bool foundIt = false;
                    string finder = fg + fd;
                    foreach (string fn in fileList)
                    {
                        if (fn.ToUpper().Contains(finder))
                        {
                            pfiles.Add(fn);
                        }

                    }
                    fgCount++;

                }
                if (fgCount == pfiles.Count())
                {
                    foreach (string fn in pfiles)
                    {
                        procFileList.Add(fn);
                    }
                    pfiles.Clear();
                }
                else
                {
                    pfiles.Clear();
                }
            }
        }

        return;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have to process files everyday.  The files are named like so:

 fg1a.mmddyyyy
 fg1b.mmddyyyy
 fg1c.mmddyyyy

 fg2a.mmddyyyy
 fg2b.mmddyyyy
 fg2c.mmddyyyy
 fg2d.mmddyyyy

If the entire file group is there for a particular date, I can process it.  If it isn't there, I should not process it.  I may have several partial file groups that run over several days.  So when I have fg1a.12062017, fg1b.12062017 and fg1c.12062017, I can process that group (fg1) only.

Here is my code so far.  It doesn't work because I can't figure out how to get only the full groups to add to the the processing file list.

        fileList = Directory.GetFiles(@"c:\temp\");

        string[] fileGroup1 = { "FG1A", "FG1B", "FG1C" }; // THIS IS A FULL GROUP
        string[] fileGroup2 = { "FG2A", "FG2B", "FG2C", "FG2D" };

        List<string> fileDates = new List<string>();
        List<string> procFileList;

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        bool allFiles = true;
        foreach (string fg in fileGroup1)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }

                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }

            }

        }

        foreach (string fg in fileGroup2)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }
                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }
            }

        }

Any help or advice would be greatly appreciated.

Body:
With everyone's help, I solved it too.  This is what I'm going with because it's the most maintainable for me but the solutions were so smart!!!  Thanks everyone for your help.

   private void CheckFiles()
    {
        var fileGroups = new[] {
          new [] { "FG1A", "FG1B", "FG1C", "FG1D" },
          new[] { "FG2A", "FG2B", "FG2C", "FG2D", "FG2E" } };

        List<string> fileDates = new List<string>();
        List<string> pfiles = new List<string>();

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        // check if a date has all the files
        foreach (string fd in fileDates)
        {
            int fgCount = 0;
            // for each file group
            foreach (Array masterfg in fileGroups)
            {
                foreach (string fg in masterfg)
                {
                    // see if all the files are there
                    bool foundIt = false;
                    string finder = fg + fd;
                    foreach (string fn in fileList)
                    {
                        if (fn.ToUpper().Contains(finder))
                        {
                            pfiles.Add(fn);
                        }

                    }
                    fgCount++;

                }
                if (fgCount == pfiles.Count())
                {
                    foreach (string fn in pfiles)
                    {
                        procFileList.Add(fn);
                    }
                    pfiles.Clear();
                }
                else
                {
                    pfiles.Clear();
                }
            }
        }

        return;
    }


问:
NUnit 3 Extension to Fail Test on a Failed Debug.Assert
I'm trying to write a NUnit 3 (3.8.1) extension that lets a test fail if it has a failed Debug.Assert(...) (instead of silently run through or even hang because it shows the failed assertion dialog).

In a NUnit 2 addin, I was able to so by unregistering all debug trace listeners and adding my own that just throws an exception (as for example explained here). However, this doesn't seem to work on NUnit 3 anymore.

I'm able to successfully deploy the extension and it's code is being executed.

```<code>[Extension(Description = "Failed Assertions Tracker", EngineVersion = "3.4")]
public class TrackerEventListener : ITestEventListener
{
    public void OnTestEvent(string report)
    {
        Console.WriteLine(report); // prints -> so I know this method is being called
        Debug.Listeners.Clear();
        Debug.Listeners.Add(new UnitTestTraceListener());
    }
}
</code>```

However, my unit test unfortunately shows me that still the DefaultTraceListener is installed.

```<code>[Test]
public void FailingAssertionShouldNotHang()
{
    foreach (object listener in Debug.Listeners)
    {
        Console.WriteLine(listener.GetType().FullName);
    }
    Debug.Fail("I'm sorry. I've failed.");
}
</code>```

And so the test shows the dialog instead of simply failing.

What am I doing wrong? I suspect that the call to the static Listeners collection is ineffective because the actual test is run in a different context (different AppDomain, process, ?). But if this is the case, how can I solve my problem?

答:
It's important to keep in mind that NUnit 3 Extensions, while capable of replacing NUnit 2 Addins in a few cases, are actually entirely different technology. NUnit 3 Extensions extend the Engine, which is separate from the framework.

In this case, your extension is setting up a Trace Listener that will capture any Debug Trace or Assert output produced by the engine. If the engine contained Trace statements (it doesn't) you would get the output. Meanwhile, the framework is happily continuing to run tests on its own.

Any code that will successfully capture Trace has to be part of the actual framework execution of the tests. This gives you two options.

Create a custom attribute that will capture trace. Custom attributes allow you to take actions when a test is being created or executed. They are created by implementing various interfaces supported by the framework. In your case, you would want to supply the attribute at assembly level, in order to capture all output produced by the assembly.

Create the code as part of your tests themself, without extending the framework at all. You would want to capture the Trace output in an assembly-level SetUpFixture using the OneTimeSetUp attribute and release it under the OneTimeTearDown attribute. Since this approach is simpler than creating a custom attribute, it's the one I would use.

Body:
I'm trying to write a NUnit 3 (3.8.1) extension that lets a test fail if it has a failed Debug.Assert(...) (instead of silently run through or even hang because it shows the failed assertion dialog).

In a NUnit 2 addin, I was able to so by unregistering all debug trace listeners and adding my own that just throws an exception (as for example explained here). However, this doesn't seem to work on NUnit 3 anymore.

I'm able to successfully deploy the extension and it's code is being executed.

[Extension(Description = "Failed Assertions Tracker", EngineVersion = "3.4")]
public class TrackerEventListener : ITestEventListener
{
    public void OnTestEvent(string report)
    {
        Console.WriteLine(report); // prints -> so I know this method is being called
        Debug.Listeners.Clear();
        Debug.Listeners.Add(new UnitTestTraceListener());
    }
}

However, my unit test unfortunately shows me that still the DefaultTraceListener is installed.

[Test]
public void FailingAssertionShouldNotHang()
{
    foreach (object listener in Debug.Listeners)
    {
        Console.WriteLine(listener.GetType().FullName);
    }
    Debug.Fail("I'm sorry. I've failed.");
}

And so the test shows the dialog instead of simply failing.

What am I doing wrong? I suspect that the call to the static Listeners collection is ineffective because the actual test is run in a different context (different AppDomain, process, ?). But if this is the case, how can I solve my problem?


问:
Use Regex in registry_data_exists Resource in Chef Recipe
I am creating a chef recipe and trying to create/update Registry key using registry_key resource. How I can use regex to validate the presence of the registry key and only update if it is necessary

registry_key'HKLM\\Software\\Microsoft\\WindowsNT\\CurrentVersion\\Winlogon' do
    values [{
    name: 'SCRemoveOption',
    type: :string,
    data: '1', }]
    #  recursive true
    action :create
    not_if { registry_data_exists?('HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon',{ name: 'SCRemoveOption', type: :string, data: '1' } ,:x86_64) }
end

If the registry key exists with data 1 or 2 or 3, There is no need to udpate or else the registry_key-data should be updated to 1.

```<code>not_if { registry_data_exists?('HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon',{ name: 'SCRemoveOption', type: :string, data: '([1-3])'} ,:x86_64) }
</code>```

答:
(Apologies for previous effort)

I have preferred using a powershell_script resource as I know PS syntax better than ruby/Chef. I used to check with Security Policy was enabled/disabled as follows:-

```<code>  powershell_script 'my_script' do
    guard_interpreter :powershell_script
    cwd 'C:\Temp'
    code <<-EOH
      <...set the registry key(s)...>
    EOH
    not_if '(get-itemproperty HKLM:\\System\\CurrentControlSet\\Control\\Lsa).DisableDomainCreds -eq "1"'
  end
</code>```

Perhaps you can adapt to make it work with an array or values.

Body:
I am creating a chef recipe and trying to create/update Registry key using registry_key resource. How I can use regex to validate the presence of the registry key and only update if it is necessary

registry_key'HKLM\\Software\\Microsoft\\WindowsNT\\CurrentVersion\\Winlogon' do
    values [{
    name: 'SCRemoveOption',
    type: :string,
    data: '1', }]
    #  recursive true
    action :create
    not_if { registry_data_exists?('HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon',{ name: 'SCRemoveOption', type: :string, data: '1' } ,:x86_64) }
end

If the registry key exists with data 1 or 2 or 3, There is no need to udpate or else the registry_key-data should be updated to 1.

not_if { registry_data_exists?('HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon',{ name: 'SCRemoveOption', type: :string, data: '([1-3])'} ,:x86_64) }

Body:
(Apologies for previous effort)

I have preferred using a powershell_script resource as I know PS syntax better than ruby/Chef. I used to check with Security Policy was enabled/disabled as follows:-

  powershell_script 'my_script' do
    guard_interpreter :powershell_script
    cwd 'C:\Temp'
    code <<-EOH
      <...set the registry key(s)...>
    EOH
    not_if '(get-itemproperty HKLM:\\System\\CurrentControlSet\\Control\\Lsa).DisableDomainCreds -eq "1"'
  end

Perhaps you can adapt to make it work with an array or values.


问:
Flexbox wrap to next line with available space
Using Flexbox I can not seem to make a div wrap to a new line without having it break with previous block content.

I made a codepen to explain:

.container {
  left: 0;
  right: 0;
  margin: auto;
  background-color: grey;
  width: 800px;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}

.lightblue {
  background-color: lightblue;
  width: 300px;
  height: 100px;
  display: block;
}

.lightpink {
  background-color: lightpink;
  width: 300px;
  height: 50px;
}

.red {
  background-color: red;
  width: 300px;
  height: 50px;
}

body {
  margin 0;
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="lightblue"></div>
  <div class="lightpink"></div>
  <div class="red"></div>
</div></code>```

What I want is for the red block to display inline, to the right of my lightblue block.

Can you tell me how to achieve this effect?

Thanks!

答:
.container {
  left: 0;
  right: 0;
  margin: auto;
  background-color: grey;
  width: 800px;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}

.lightblue {
  background-color: lightblue;
  width: 300px;
  height: 100px;
  display: block;
}

.lightpink {
  background-color: lightpink;
  width: 300px;
  height: 50px;
}

.red {
  background-color: red;
  width: 300px;
  height: 50px;
}

body {
   margin 0;
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="lightblue" ></div>
  <div>
      <div class="lightpink" ></div>
      <div class="red" ></div>
  </div>
</div></code>```

You just wrap .lightpink, .red in div.

Body:
Using Flexbox I can not seem to make a div wrap to a new line without having it break with previous block content.

I made a codepen to explain:

.container {
  left: 0;
  right: 0;
  margin: auto;
  background-color: grey;
  width: 800px;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}

.lightblue {
  background-color: lightblue;
  width: 300px;
  height: 100px;
  display: block;
}

.lightpink {
  background-color: lightpink;
  width: 300px;
  height: 50px;
}

.red {
  background-color: red;
  width: 300px;
  height: 50px;
}

body {
  margin 0;
  width: 100%;
  height: 100%;
}

What I want is for the red block to display inline, to the right of my lightblue block.

Can you tell me how to achieve this effect?

Thanks!

Body:
.container {
  left: 0;
  right: 0;
  margin: auto;
  background-color: grey;
  width: 800px;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}

.lightblue {
  background-color: lightblue;
  width: 300px;
  height: 100px;
  display: block;
}

.lightpink {
  background-color: lightpink;
  width: 300px;
  height: 50px;
}

.red {
  background-color: red;
  width: 300px;
  height: 50px;
}

body {
   margin 0;
  width: 100%;
  height: 100%;
}

<div class="container">

  <div class="lightblue" ></div>
  <div>
      <div class="lightpink" ></div>
      <div class="red" ></div>
  </div>
</div>

You just wrap .lightpink, .red in div.


问:
Deploy SSRS reports on a customer's machine with PowerShell
We are developing some reports locally. These reports are to be installed on a customer's machine. But we cannot reach this machine online.

What I've managed so far:

A folder containing:

all report objects (data source, data sets and reports)

a copy of the PowerShell module ReportingServicesTools

a PowerShell script

This script will create all needed folders within ReportServer, load the data source, then the data sets and finally the reports. This works, I can open the portal and can see my objects.

UPDATE:

The downloaded rdl files had their data-set-references set to the plain dataset's name - why ever... It took me hours to find, that the reference must include the full (internal) path to the dataset... Now the paginated reports really work, heureka!

The Questions

This does not work for

mobile reports (aka dashboards, but not PowerBI)

our branding file

How can mobile reports be uploaded via PowerShell?

How can a custom branding package be uploaded?

Is there a better approach? I'm fairly new to PowerShell and therefore open to any advice! TIA

EDIT

Deleted the script fragment as I've posted a comprehensive answer myself...

UPDATE: No answer yet?

At the bottom of my own answer there are some open questions... I'd love to give the bounty to somebody but it seems to be lost... Anyway: If Anybode might answer at least part of the remaining open questions there's a good chance for 150 points :-)

答:
Microsoft decided to let us poor tech staff alone with this...

The issues I've found so far:

After deletion of shared dataset all mobile reports must be re-created from scratch (a re-mapping of datasources is not supported). This is by design, read this, if you cannot believe it

Deployment is supported to a reachable server only (via target URL)

There is currently no support to upload a mobile report other than via SSRS portal

There is currently no support to upload a branding package other than via SSRS portal

As nobody seems to be able to help - even with a bounty! - I'll state what I've found so far:

The following PowerShellScript is a working stand-alone deployment on a disconnected machine.

Assumptions:

All SSRS-objects (.rsd, .rdl and .rsmobile) are downloaded and are living in appropriate directories below "DeployDirectory"

In my case all shared data set filles are in  folder "MyProduct Data"

In my case all reports are living within sub-folders "EventLog", "Public Reports" and "Report Audit"

It would be possible to automate the folders structure, but in this script this part is hard-coded to my needs.

The PowerShell-Module ReportingServicesTools is placed within a directory
with the same name below "DeployDirectory"

A shared data set's name is globally unique (this is not mandatory by SSRS)

Good luck with this!

```<code>$DeployDirectory=".\MyProduct Reports\"
$DbURL="1.2.3.4"
$srvURI="http://1.2.3.4/ReportServer"
$srvURL="http://1.2.3.4/reports"

#Write RS Report folders
$rootDir="/MyProduct Reports"
</code>```

#Import the module and create folders. This might be automated too (out of the directory structure found on disc, but this is up to you...)

```<code>Import-Module  .\ReportingServicesTools
New-RsFolder -ReportServerUri $srvURI -Path "/"      -Name "MyProduct Reports"
New-RsFolder -ReportServerUri $srvURI -Path $rootDir -Name "MyProduct Data"
New-RsFolder -ReportServerUri $srvURI -Path $rootDir -Name "EventLog"
New-RsFolder -ReportServerUri $srvURI -Path $rootDir -Name "Public Reports"
New-RsFolder -ReportServerUri $srvURI -Path $rootDir -Name "Report Audit"
Write-Host "RS Report folders written"
</code>```

#Create shared data source

```<code>New-RsDataSource -RsFolder ($rootDir + "/MyProduct Data") -Name "MyProduct_DatabaseConnection" -Extension "SQL" -ConnectionString ("Data Source=" +  $DbURL + ";Integrated Security=True;Initial Catalog=master;") -CredentialRetrieval "Integrated"
Write-Host "Shared data source created"
</code>```

#Modify shared data set files: The hardcoded reference to the server's URL must be changed

```<code>$allRSDs = Get-ChildItem -Recurse -Path $DeployDirectory | Where-Object -FilterScript {$_.Extension -eq ".rsd"}
Write-Host "RSDs fetched"

$xml = New-Object System.Xml.XmlDocument
$nsMngr = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$nsMngr.AddNamespace("rd","http://schemas.microsoft.com/SQLServer/reporting/reportdesigner")
$allRSDs | % {
               $FileName=$_.FullName;
               $xml.Load($FileName);
               $xml.SelectNodes("//rd:ReportServerUrl",$nsMngr) |
               % {$_.InnerText=$srvURI};
               $newContent = $xml.InnerXml;
               Set-Content -Path $FileName -Value $newContent
             }
Write-Host "Shared data set files modified"

Write-RsFolderContent -Recurse -ReportServerUri $srvURI -Path ($DeployDirectory + "MyProduct Data") -RsFolder ($rootDir + "/MyProduct Data")
Write-Host "Shared DataSets created"
</code>```

#Read all created shared data sets out of the database into a table variable

```<code>$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString=("Data Source=" + $DbURL + ";Integrated Security=True;Initial Catalog=master;")
$con.Open();
Write-Host "connection opened"

$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.Connection = $con
Write-Host "command created"

$cmd.CommandText = "SELECT ItemID, [name] AS DataSetName, [Path] AS DataSetPath, LEN([name]) AS SortOrder `
                    FROM ReportServer.dbo.[Catalog]`
                    WHERE [Type]=8"
$adapt = New-Object System.Data.SqlClient.SqlDataAdapter
$adapt.SelectCommand = $cmd
$ds = New-Object System.Data.DataSet
$adapt.Fill($ds)
$allDs = New-Object System.Data.DataTable
$allDs = $ds.Tables[0]
Write-Host "shared datasets fetched into cache"

Class shDs {[string]$ItemId=""; [string]$DataSetName=""; [string]$DataSetPath="";}
function Get-SharedDataSet([string]$DataSetName){
    $retVal = New-Object shDs
    $Search = ("'" + $DataSetName + "' LIKE DataSetName + '%'")
    $Sort = ("SortOrder DESC")
    $dsRow = $allDs.Select($Search,$Sort)[0]
    $retVal.ItemID=$dsRow["ItemID"].ToString().Trim()
    $retVal.DataSetPath=$dsRow["DataSetPath"].ToString().Trim()
    $retVal.DataSetName=$dsRow["DataSetName"].ToString().Trim()
    return $retVal
}
Write-Host "function to fetch referenced shared dataset created"
$con.Close()
Write-Host "connection closed"
</code>```

#Modify paginated report files: The newly written shared datasets must be written into the report-XML

```<code>$allRDLs = (Get-ChildItem -Recurse -Path $DeployDirectory |
                Where-Object -FilterScript {$_.Extension -eq ".rdl"})
$xml = New-Object System.Xml.XmlDocument
$nsMngr = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$nsMngr.AddNamespace("rd","http://schemas.microsoft.com/SQLServer/reporting/reportdesigner")
$nsMngr.AddNamespace("ns","http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition")
$allRDLs | % {
               $FileName=$_.FullName;
               $xml.Load($FileName);
               $xml.SelectNodes("//rd:ReportServerUrl",$nsMngr) |
                  % {$_.InnerText=$srvURI};
               $xml.SelectNodes("//ns:SharedDataSetReference",$nsMngr) |
                  % {
                       $it = ("/" + $_.Innertext);
                       $ref=$it.SubString($it.LastIndexOf("/")+1);
                       $ds = Get-SharedDataSet($ref);
                       $_.InnerText=$ds.DataSetPath
                       Write-Host ("DataSetPath: " + $_.InnerText)
                    };
               $newContent = $xml.InnerXml;
               Set-Content -Path $FileName -Value $newContent
             }
Write-Host "paginated report files modified"

Write-RsFolderContent -Recurse -ReportServerUri $srvURI -Path ($DeployDirectory + "EventLog") -RsFolder ($rootDir + "/EventLog")
Write-RsFolderContent -Recurse -ReportServerUri $srvURI -Path ($DeployDirectory + "Public Reports") -RsFolder ($rootDir + "/Public Reports")
Write-RsFolderContent -Recurse -ReportServerUri $srvURI -Path ($DeployDirectory + "Report Audit") -RsFolder ($rootDir + "/Report Audit")
Write-Host "paginated reports created"
</code>```

#Modify mobile report files: This is more complicated... The files are ZIPs actually. These ZIPs contain several files. The metadata.xml and the sources.xml contain hard-coded references and must be changed

```<code>$allMobs = (Get-ChildItem -Recurse -Path $DeployDirectory |
                Where-Object -FilterScript {$_.Extension -eq ".rsmobile"})

#Unzip SomeName.rsmobile into SomeName.rsmobile.Unzipped
Add-Type -AssemblyName System.IO.Compression.FileSystem
Add-Type -AssemblyName System.Collections
$unzippedList = New-Object System.Collections.ArrayList
Class zippedMobs {[string]$DirectoryName; [string]$rsMobileName; [string]$FileName;}
Get-ChildItem -Recurse $path |
    Where-Object -FilterScript {$_.Extension -eq ".rsmobile"} |
    % {
       $zm = New-Object zippedMobs;
       $zm.DirectoryName = ($_.FullName + ".Unzipped");
       $zm.rsMobileName=$_.FullName;
       $zm.FileName=$_.Name;
       $unzippedList.Add($zm);
       [System.IO.Compression.ZipFile]::ExtractToDirectory($zm.rsMobileName,$zm.DirectoryName)
      }
Write-Host "Mobile Reports: Files unzipped"
</code>```

#Open all metadata.xml files in all unzipped folders and modify them

```<code>$xml = New-Object System.Xml.XmlDocument
$nsMngr = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$nsMngr.AddNamespace("ns","http://schemas.microsoft.com/sqlserver/reporting/2016/02/mobilereportpackage")
$nsMngr.AddNamespace("mrp","http://schemas.microsoft.com/sqlserver/reporting/2016/02/mobilereportpublisher")
$unzippedList | % {
         $FileName=($_.DirectoryName + "\metadata.xml");
         $xml.Load($FileName);
         $xml.SelectNodes("//ns:dataSet",$nsMngr) |
            % {
                $ref=$_.Attributes["name"].Value;
                $ds = Get-SharedDataSet($ref);
                $_.Attributes["mrp:Server"].Value=$srvURL;
                $_["id"].InnerText=$ds.ItemID;
                $_["path"].InnerText=$ds.DataSetPath
              };
         $newContent = $xml.InnerXml;
         Set-Content -Path $FileName -Value $newContent
        }
Write-Host "Mobile Reports: All metadata.xml re-mapped"
</code>```

#Open all sources.xml files in all unzipped folders and modify them

```<code>$xml = New-Object System.Xml.XmlDocument
$unzippedList | % {
         $FileName=($_.DirectoryName + "\sources.xml");
         $xml.Load($FileName);
         $xml.SelectNodes("//Shared") |
            % {
             $ref=$_.Attributes["Name"].Value;
             $ds = Get-SharedDataSet($ref);
             $_.Attributes["ServerUri"].Value=$srvURL;
             $_.Attributes["Guid"].Value=$ds.ItemID;
             $_.Attributes["DataItemLocation"].Value=$ds.DataSetPath
            };
         $newContent = $xml.InnerXml;
         Set-Content -Path $FileName -Value $newContent
        }
Write-Host "Mobile Reports: All sources.xml re-mapped"
</code>```

#Rename all original .rsmobile files

```<code>$unzippedList | % {Rename-Item -Path $_.rsMobileName -NewName ($_.FileName + ".old")}
Write-Host "Mobile Reports: Renamed all orginal .rsmobile files"
#Create new ZIP file for all mobile reports
$unzippedList | % {
                   [System.IO.Compression.ZipFile]::CreateFromDirectory($_.DirectoryName,$_.rsMobileName,[System.IO.Compression.CompressionLevel]::NoCompression, $FALSE)
                  }
Write-Host "Re-created all mobile report files"
</code>```

Attention

Allthough the created ZIP-files (the new .rsmobile files) are valid and contain the correct content, it is impossible to upload them via SSRS portal (error: invalid report package). But - funny enough! - when you use explorer's send to compressed directory and rename the resulting ZIP file accordingly, this can be uploaded.

Still open questions:

How can one create the .rsmobile (ZIP-file) that it is uploadable? (must be the same way of zipping as windows does it implicitly when sending to a compressed folder)

How can one upload a mobile report programmatically?

This one I could answer in the meanwhile (see second answer):

How can one upload a branding package programmatically?

Body:
Microsoft decided to let us poor tech staff alone with this...

The issues I've found so far:

After deletion of shared dataset all mobile reports must be re-created from scratch (a re-mapping of datasources is not supported). This is by design, read this, if you cannot believe it

Deployment is supported to a reachable server only (via target URL)

There is currently no support to upload a mobile report other than via SSRS portal

There is currently no support to upload a branding package other than via SSRS portal

As nobody seems to be able to help - even with a bounty! - I'll state what I've found so far:

The following PowerShellScript is a working stand-alone deployment on a disconnected machine.

Assumptions:

All SSRS-objects (.rsd, .rdl and .rsmobile) are downloaded and are living in appropriate directories below "DeployDirectory"

In my case all shared data set filles are in  folder "MyProduct Data"

In my case all reports are living within sub-folders "EventLog", "Public Reports" and "Report Audit"

It would be possible to automate the folders structure, but in this script this part is hard-coded to my needs.

The PowerShell-Module ReportingServicesTools is placed within a directory
with the same name below "DeployDirectory"

A shared data set's name is globally unique (this is not mandatory by SSRS)

Good luck with this!

$DeployDirectory=".\MyProduct Reports\"
$DbURL="1.2.3.4"
$srvURI="http://1.2.3.4/ReportServer"
$srvURL="http://1.2.3.4/reports"

#Write RS Report folders
$rootDir="/MyProduct Reports"

#Import the module and create folders. This might be automated too (out of the directory structure found on disc, but this is up to you...)

Import-Module  .\ReportingServicesTools
New-RsFolder -ReportServerUri $srvURI -Path "/"      -Name "MyProduct Reports"
New-RsFolder -ReportServerUri $srvURI -Path $rootDir -Name "MyProduct Data"
New-RsFolder -ReportServerUri $srvURI -Path $rootDir -Name "EventLog"
New-RsFolder -ReportServerUri $srvURI -Path $rootDir -Name "Public Reports"
New-RsFolder -ReportServerUri $srvURI -Path $rootDir -Name "Report Audit"
Write-Host "RS Report folders written"

#Create shared data source

New-RsDataSource -RsFolder ($rootDir + "/MyProduct Data") -Name "MyProduct_DatabaseConnection" -Extension "SQL" -ConnectionString ("Data Source=" +  $DbURL + ";Integrated Security=True;Initial Catalog=master;") -CredentialRetrieval "Integrated"
Write-Host "Shared data source created"

#Modify shared data set files: The hardcoded reference to the server's URL must be changed

$allRSDs = Get-ChildItem -Recurse -Path $DeployDirectory | Where-Object -FilterScript {$_.Extension -eq ".rsd"}
Write-Host "RSDs fetched"

$xml = New-Object System.Xml.XmlDocument
$nsMngr = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$nsMngr.AddNamespace("rd","http://schemas.microsoft.com/SQLServer/reporting/reportdesigner")
$allRSDs | % {
               $FileName=$_.FullName;
               $xml.Load($FileName);
               $xml.SelectNodes("//rd:ReportServerUrl",$nsMngr) |
               % {$_.InnerText=$srvURI};
               $newContent = $xml.InnerXml;
               Set-Content -Path $FileName -Value $newContent
             }
Write-Host "Shared data set files modified"

Write-RsFolderContent -Recurse -ReportServerUri $srvURI -Path ($DeployDirectory + "MyProduct Data") -RsFolder ($rootDir + "/MyProduct Data")
Write-Host "Shared DataSets created"

#Read all created shared data sets out of the database into a table variable

$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString=("Data Source=" + $DbURL + ";Integrated Security=True;Initial Catalog=master;")
$con.Open();
Write-Host "connection opened"

$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.Connection = $con
Write-Host "command created"

$cmd.CommandText = "SELECT ItemID, [name] AS DataSetName, [Path] AS DataSetPath, LEN([name]) AS SortOrder `
                    FROM ReportServer.dbo.[Catalog]`
                    WHERE [Type]=8"
$adapt = New-Object System.Data.SqlClient.SqlDataAdapter
$adapt.SelectCommand = $cmd
$ds = New-Object System.Data.DataSet
$adapt.Fill($ds)
$allDs = New-Object System.Data.DataTable
$allDs = $ds.Tables[0]
Write-Host "shared datasets fetched into cache"

Class shDs {[string]$ItemId=""; [string]$DataSetName=""; [string]$DataSetPath="";}
function Get-SharedDataSet([string]$DataSetName){
    $retVal = New-Object shDs
    $Search = ("'" + $DataSetName + "' LIKE DataSetName + '%'")
    $Sort = ("SortOrder DESC")
    $dsRow = $allDs.Select($Search,$Sort)[0]
    $retVal.ItemID=$dsRow["ItemID"].ToString().Trim()
    $retVal.DataSetPath=$dsRow["DataSetPath"].ToString().Trim()
    $retVal.DataSetName=$dsRow["DataSetName"].ToString().Trim()
    return $retVal
}
Write-Host "function to fetch referenced shared dataset created"
$con.Close()
Write-Host "connection closed"

#Modify paginated report files: The newly written shared datasets must be written into the report-XML

$allRDLs = (Get-ChildItem -Recurse -Path $DeployDirectory |
                Where-Object -FilterScript {$_.Extension -eq ".rdl"})
$xml = New-Object System.Xml.XmlDocument
$nsMngr = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$nsMngr.AddNamespace("rd","http://schemas.microsoft.com/SQLServer/reporting/reportdesigner")
$nsMngr.AddNamespace("ns","http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition")
$allRDLs | % {
               $FileName=$_.FullName;
               $xml.Load($FileName);
               $xml.SelectNodes("//rd:ReportServerUrl",$nsMngr) |
                  % {$_.InnerText=$srvURI};
               $xml.SelectNodes("//ns:SharedDataSetReference",$nsMngr) |
                  % {
                       $it = ("/" + $_.Innertext);
                       $ref=$it.SubString($it.LastIndexOf("/")+1);
                       $ds = Get-SharedDataSet($ref);
                       $_.InnerText=$ds.DataSetPath
                       Write-Host ("DataSetPath: " + $_.InnerText)
                    };
               $newContent = $xml.InnerXml;
               Set-Content -Path $FileName -Value $newContent
             }
Write-Host "paginated report files modified"

Write-RsFolderContent -Recurse -ReportServerUri $srvURI -Path ($DeployDirectory + "EventLog") -RsFolder ($rootDir + "/EventLog")
Write-RsFolderContent -Recurse -ReportServerUri $srvURI -Path ($DeployDirectory + "Public Reports") -RsFolder ($rootDir + "/Public Reports")
Write-RsFolderContent -Recurse -ReportServerUri $srvURI -Path ($DeployDirectory + "Report Audit") -RsFolder ($rootDir + "/Report Audit")
Write-Host "paginated reports created"

#Modify mobile report files: This is more complicated... The files are ZIPs actually. These ZIPs contain several files. The metadata.xml and the sources.xml contain hard-coded references and must be changed

$allMobs = (Get-ChildItem -Recurse -Path $DeployDirectory |
                Where-Object -FilterScript {$_.Extension -eq ".rsmobile"})

#Unzip SomeName.rsmobile into SomeName.rsmobile.Unzipped
Add-Type -AssemblyName System.IO.Compression.FileSystem
Add-Type -AssemblyName System.Collections
$unzippedList = New-Object System.Collections.ArrayList
Class zippedMobs {[string]$DirectoryName; [string]$rsMobileName; [string]$FileName;}
Get-ChildItem -Recurse $path |
    Where-Object -FilterScript {$_.Extension -eq ".rsmobile"} |
    % {
       $zm = New-Object zippedMobs;
       $zm.DirectoryName = ($_.FullName + ".Unzipped");
       $zm.rsMobileName=$_.FullName;
       $zm.FileName=$_.Name;
       $unzippedList.Add($zm);
       [System.IO.Compression.ZipFile]::ExtractToDirectory($zm.rsMobileName,$zm.DirectoryName)
      }
Write-Host "Mobile Reports: Files unzipped"

#Open all metadata.xml files in all unzipped folders and modify them

$xml = New-Object System.Xml.XmlDocument
$nsMngr = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$nsMngr.AddNamespace("ns","http://schemas.microsoft.com/sqlserver/reporting/2016/02/mobilereportpackage")
$nsMngr.AddNamespace("mrp","http://schemas.microsoft.com/sqlserver/reporting/2016/02/mobilereportpublisher")
$unzippedList | % {
         $FileName=($_.DirectoryName + "\metadata.xml");
         $xml.Load($FileName);
         $xml.SelectNodes("//ns:dataSet",$nsMngr) |
            % {
                $ref=$_.Attributes["name"].Value;
                $ds = Get-SharedDataSet($ref);
                $_.Attributes["mrp:Server"].Value=$srvURL;
                $_["id"].InnerText=$ds.ItemID;
                $_["path"].InnerText=$ds.DataSetPath
              };
         $newContent = $xml.InnerXml;
         Set-Content -Path $FileName -Value $newContent
        }
Write-Host "Mobile Reports: All metadata.xml re-mapped"

#Open all sources.xml files in all unzipped folders and modify them

$xml = New-Object System.Xml.XmlDocument
$unzippedList | % {
         $FileName=($_.DirectoryName + "\sources.xml");
         $xml.Load($FileName);
         $xml.SelectNodes("//Shared") |
            % {
             $ref=$_.Attributes["Name"].Value;
             $ds = Get-SharedDataSet($ref);
             $_.Attributes["ServerUri"].Value=$srvURL;
             $_.Attributes["Guid"].Value=$ds.ItemID;
             $_.Attributes["DataItemLocation"].Value=$ds.DataSetPath
            };
         $newContent = $xml.InnerXml;
         Set-Content -Path $FileName -Value $newContent
        }
Write-Host "Mobile Reports: All sources.xml re-mapped"

#Rename all original .rsmobile files

$unzippedList | % {Rename-Item -Path $_.rsMobileName -NewName ($_.FileName + ".old")}
Write-Host "Mobile Reports: Renamed all orginal .rsmobile files"
#Create new ZIP file for all mobile reports
$unzippedList | % {
                   [System.IO.Compression.ZipFile]::CreateFromDirectory($_.DirectoryName,$_.rsMobileName,[System.IO.Compression.CompressionLevel]::NoCompression, $FALSE)
                  }
Write-Host "Re-created all mobile report files"

Attention

Allthough the created ZIP-files (the new .rsmobile files) are valid and contain the correct content, it is impossible to upload them via SSRS portal (error: invalid report package). But - funny enough! - when you use explorer's send to compressed directory and rename the resulting ZIP file accordingly, this can be uploaded.

Still open questions:

How can one create the .rsmobile (ZIP-file) that it is uploadable? (must be the same way of zipping as windows does it implicitly when sending to a compressed folder)

How can one upload a mobile report programmatically?

This one I could answer in the meanwhile (see second answer):

How can one upload a branding package programmatically?


问:
Hosting Silverlight in C++
I'm a bit over my head here and would like some advice on how to go about.

Basicly what I want to do is to be able to render and control silverlight inside my C++ application. I would like something as:

```<code>class silverlight_host
{
public:
     // Prio 1
     silverlight_host(const std::string& filename); // Load a xap file
     void draw(void* dest); // Draw with alpha to dest
     std::pair<size_t, size_t> get_size(); // Need to know required size of dest

     // Prio 2
     bool is_dirty() const; // Check for dirty rect since last call to draw
     void send_param(const std::string& param); // Send data to silverlight control or call functions. Alternative name maybe, call_function
     void set_size(size_t width, size_t height); // Set the size of drawing.

     // Prio 3
     // Some more nice to have functions, although not as important as those above
     double get_desired_frame_rate(); // The desired frame rate which is specified in xap
     std::pair<size_t, size_t> get_desired_size(); // The desired size which is specified in xap
     void tick(); // Tick a synchronous timeline, disable internal asynchronous timer
     void set_param_callback(const std::function<void(const std::string&)>& callback); // Let the xap file call the application
};
</code>```

Easier said than done. I have found the following articles Host Silverlight Contorl in C++ and Communication between C++ Silverlight Host and Silverlight Application. My problem with these are that the provided code doesn't seem to work when compiled in VS2010 and they create an actual window instead of a windowless control. Also what happens is not very well explained and I am somewhat lacking in COM and ATL knowledge.

I've also found this which seems to have a simpler way to implement the xcpcontrolhost than the articles above.

I have found some reference information on msdn. Where ISilverlightViewer seems quite interesting for my needs. In order to allow a windowless control I believe that I probably have to implement something like IOleInPlaceSiteWindowless?.

However, I am quite a bit over my head here and I'm unsure where to even begin. I'd like to ask some advice regarding where I should get started and if you have any general advice or experience with something like this?

EDIT: Something which would also be interesting, although quite secondary, would be if such an implementation could be made platform independent?

EDIT2: I have modified the code in "TestProject" from one of the articles above. I have tried to remove redundant code and fixed it so that it runs on VS2010 (according to answer below). You can find it here.

EDIT3:

I have tried to implement a windowless XcpControlHost class. I've looked at the code in CAxHostWindow and tried to re-create it. The reason I don't use CAxHostWindow to create a windowless control is that it does not support alpha.

It seems to compile fine, however when I call DrawControl I only get back a black frame.

XcpContorlHost.h
XcpControlHost.cpp

Any ideas as to what might be wrong?

EDIT4: I'm taking a step back. I use the code from "TestProject" I want to modify CreateXcpControl(HWND hWnd) to be able to take hWnd == nullptr (windowless) and use OleDraw to draw the control to memory.

Soo what I tried to do is to simply bypass the call to "AttachControl" and directly call "ActivateXcpControl". And I've replaced GetClientRect by hard-coded values.

```<code>STDMETHODIMP XcpControlHost::AttachControl(IUnknown* pUnKnown, HWND hWnd)
{
    assert(hWnd == nullptr);
    ReleaseAll();
    // Removed all hWnd related code
    return ActivateXcpControl(pUnKnown);
}

HRESULT XcpControlHost::ActivateXcpControl(IUnknown* pUnKnown)
{
     // Lots of code
     // GetClientRect(&m_rcPos); // Remove this
     m_rcPos.top = 0;
     m_rcPos.left = 0;
     m_rcPos.right = 720;
     m_rcPos.bottom = 576;
     // Lots of code
}
</code>```

I create the XcpControlHost inside a thread with CoInitialize:

```<code>void run()
{
    struct co_init
    {
        co_init(){CoInitialize(nullptr);}
        ~co_init(){CoUninitialize();}
    } co;

    if(FAILED(CComObject<XcpControlHost>::CreateInstance(&host_)))
        throw std::exception("Failed to create XcpControlHost");

    if(FAILED(host_->CreateXcpControl()))
        throw std::exception("Failed to create XcpControl");

    while(GetMessage(&msg, 0, 0, 0))
    {
        if(!is_running_)
            PostQuitMessage(0);

        if(msg.message == WM_USER + 1) // Sent from app
            OleDraw(host_->m_pUnKnown, DVASPECT_CONTENT, targetDC, 0);

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}
</code>```

And then I run the usual windows message handler loop with GetMessage, TranslateMessage and DispatchMessage.

However, still all I get is blackness. What am I doing wrong?

I seem to get E_FAIL from the following call in "ActivateXcpControl":

```<code>hr = m_spOleObject->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, spClientSite, 0, NULL, &m_rcPos);
</code>```

答:
I have tested the code project available here: http://www.codeproject.com/KB/atl/Host_Silverlight_In_ATL.aspx under Visual Studio 2010. Here is what's needed to make it work:

load it under VS 2010 and convert it to VS 2010 (don't care about backupgs logs, etc...)

remove the registration Post-Build Event ("$(TargetPath)" /RegServer), it's only used for registration of COM components inside the projet. You can also let that event and just forget about the error if you prefer.

I had to do a small change in XcpControlHost.cpp.

Here is the change:

```<code>HRESULT CXcpControlHost::CreateXcpControl(HWND hWnd)
{
    AtlAxWinInit();
    CoInitialize(NULL); // add this line to initialize COM
    ...
}
</code>```

And it works (I'm running Windows 7 with Silverlight 4).

This is really the way to go.

One remark though: In the sample, the author does not use the official xcpctrl.idl file available from here: http://msdn.microsoft.com/en-us/library/cc296246(VS.95).aspx . Instead he redefines all interfaces and GUID, and this is not needed. You can just add the xcpctrl.idl to a Visual Studio 2010 and compile, this will trigger the MIDL compiler that will create the 3 following files: xcpctrl_h.h, xcpctrl_i.c, xcpctrl_p.c. Once they are compiled, you can add them to the project.

ContentLicense: CC BY-SA 2.5

Title: Hosting Silverlight in C++

Body:
I'm a bit over my head here and would like some advice on how to go about.

Basicly what I want to do is to be able to render and control silverlight inside my C++ application. I would like something as:

class silverlight_host
{
public:
     // Prio 1
     silverlight_host(const std::string& filename); // Load a xap file
     void draw(void* dest); // Draw with alpha to dest
     std::pair<size_t, size_t> get_size(); // Need to know required size of dest

     // Prio 2
     bool is_dirty() const; // Check for dirty rect since last call to draw
     void send_param(const std::string& param); // Send data to silverlight control or call functions. Alternative name maybe, call_function
     void set_size(size_t width, size_t height); // Set the size of drawing.

     // Prio 3
     // Some more nice to have functions, although not as important as those above
     double get_desired_frame_rate(); // The desired frame rate which is specified in xap
     std::pair<size_t, size_t> get_desired_size(); // The desired size which is specified in xap
     void tick(); // Tick a synchronous timeline, disable internal asynchronous timer
     void set_param_callback(const std::function<void(const std::string&)>& callback); // Let the xap file call the application
};

Easier said than done. I have found the following articles Host Silverlight Contorl in C++ and Communication between C++ Silverlight Host and Silverlight Application. My problem with these are that the provided code doesn't seem to work when compiled in VS2010 and they create an actual window instead of a windowless control. Also what happens is not very well explained and I am somewhat lacking in COM and ATL knowledge.

I've also found this which seems to have a simpler way to implement the xcpcontrolhost than the articles above.

I have found some reference information on msdn. Where ISilverlightViewer seems quite interesting for my needs. In order to allow a windowless control I believe that I probably have to implement something like IOleInPlaceSiteWindowless?.

However, I am quite a bit over my head here and I'm unsure where to even begin. I'd like to ask some advice regarding where I should get started and if you have any general advice or experience with something like this?

EDIT: Something which would also be interesting, although quite secondary, would be if such an implementation could be made platform independent?

EDIT2: I have modified the code in "TestProject" from one of the articles above. I have tried to remove redundant code and fixed it so that it runs on VS2010 (according to answer below). You can find it here.

EDIT3:

I have tried to implement a windowless XcpControlHost class. I've looked at the code in CAxHostWindow and tried to re-create it. The reason I don't use CAxHostWindow to create a windowless control is that it does not support alpha.

It seems to compile fine, however when I call DrawControl I only get back a black frame.

XcpContorlHost.h
XcpControlHost.cpp

Any ideas as to what might be wrong?

EDIT4: I'm taking a step back. I use the code from "TestProject" I want to modify CreateXcpControl(HWND hWnd) to be able to take hWnd == nullptr (windowless) and use OleDraw to draw the control to memory.

Soo what I tried to do is to simply bypass the call to "AttachControl" and directly call "ActivateXcpControl". And I've replaced GetClientRect by hard-coded values.

STDMETHODIMP XcpControlHost::AttachControl(IUnknown* pUnKnown, HWND hWnd)
{
    assert(hWnd == nullptr);
    ReleaseAll();
    // Removed all hWnd related code
    return ActivateXcpControl(pUnKnown);
}

HRESULT XcpControlHost::ActivateXcpControl(IUnknown* pUnKnown)
{
     // Lots of code
     // GetClientRect(&m_rcPos); // Remove this
     m_rcPos.top = 0;
     m_rcPos.left = 0;
     m_rcPos.right = 720;
     m_rcPos.bottom = 576;
     // Lots of code
}

I create the XcpControlHost inside a thread with CoInitialize:

void run()
{
    struct co_init
    {
        co_init(){CoInitialize(nullptr);}
        ~co_init(){CoUninitialize();}
    } co;

    if(FAILED(CComObject<XcpControlHost>::CreateInstance(&host_)))
        throw std::exception("Failed to create XcpControlHost");

    if(FAILED(host_->CreateXcpControl()))
        throw std::exception("Failed to create XcpControl");

    while(GetMessage(&msg, 0, 0, 0))
    {
        if(!is_running_)
            PostQuitMessage(0);

        if(msg.message == WM_USER + 1) // Sent from app
            OleDraw(host_->m_pUnKnown, DVASPECT_CONTENT, targetDC, 0);

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

And then I run the usual windows message handler loop with GetMessage, TranslateMessage and DispatchMessage.

However, still all I get is blackness. What am I doing wrong?

I seem to get E_FAIL from the following call in "ActivateXcpControl":

hr = m_spOleObject->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, spClientSite, 0, NULL, &m_rcPos);

Body:
I have tested the code project available here: http://www.codeproject.com/KB/atl/Host_Silverlight_In_ATL.aspx under Visual Studio 2010. Here is what's needed to make it work:

load it under VS 2010 and convert it to VS 2010 (don't care about backupgs logs, etc...)

remove the registration Post-Build Event ("$(TargetPath)" /RegServer), it's only used for registration of COM components inside the projet. You can also let that event and just forget about the error if you prefer.

I had to do a small change in XcpControlHost.cpp.

Here is the change:

HRESULT CXcpControlHost::CreateXcpControl(HWND hWnd)
{
    AtlAxWinInit();
    CoInitialize(NULL); // add this line to initialize COM
    ...
}

And it works (I'm running Windows 7 with Silverlight 4).

This is really the way to go.

One remark though: In the sample, the author does not use the official xcpctrl.idl file available from here: http://msdn.microsoft.com/en-us/library/cc296246(VS.95).aspx . Instead he redefines all interfaces and GUID, and this is not needed. You can just add the xcpctrl.idl to a Visual Studio 2010 and compile, this will trigger the MIDL compiler that will create the 3 following files: xcpctrl_h.h, xcpctrl_i.c, xcpctrl_p.c. Once they are compiled, you can add them to the project.


问:
How To Put Navigation In App-Route Angular 2 CLI
In my app component in the Angular CLI I want to do this...

```<code><app-navbar></app-navbar>

<router-outlet></router-outlet>
</code>```

And in the navbar component I want to do this...

```<code>this.activatedRoute.url.subscribe((url) => {
  console.log(url[0].path);
});
</code>```

But the url[0].path is always empty. I think it's because the app-navbar can't see the route as it isn't embedded in the router-outlet.

I'm confused though. I don't want to have to create an entire new route just to have navigation in (and then make everything a child). In AngularJS I could add an abstract state and then read the param in the $stateParams in the router config. But how do I do this with Angular?

答:
Here is what I would write (subscription to the router (which I guess you already have in your constructor))</p>

```<code>this.router.events.subscribe((rout) => {
      if (rout instanceof NavigationStart) {
        console.log(rout.url);
      }
    });
</code>```

Body:
In my app component in the Angular CLI I want to do this...

<app-navbar></app-navbar>

<router-outlet></router-outlet>

And in the navbar component I want to do this...

this.activatedRoute.url.subscribe((url) => {
  console.log(url[0].path);
});

But the url[0].path is always empty. I think it's because the app-navbar can't see the route as it isn't embedded in the router-outlet.

I'm confused though. I don't want to have to create an entire new route just to have navigation in (and then make everything a child). In AngularJS I could add an abstract state and then read the param in the $stateParams in the router config. But how do I do this with Angular?

Body:
Here is what I would write (subscription to the router (which I guess you already have in your constructor))

this.router.events.subscribe((rout) => {
      if (rout instanceof NavigationStart) {
        console.log(rout.url);
      }
    });


问:
Can we use both Google anlytics and firebase at a time?
I was trying to integrate the firebase analytics in my iOS app, but Xcode is throwing an issue missing tracker id, there are two GoogleService-Info.plist which I added in Xcode root directory. Many devs says to totally remove google analytics pod and use firebase analytics. But I need both. Can someone help me out. Thanks in advance.</p>

答: I finally made it by removing pod 'google/analytics' and replacing the pod with pod 'GoogleAnalytics', and the GoogleService-Info.plist should be added to root directory of the project as well as in copy bundle resources. Both GA and firebase analytics are working. </p>


问:
Karate API pass def variable in XML
I defined a variable with

```<code>* def token = '1bce02b8..'
</code>```

I would like to retrieve the variable I defined so I can pass this to my SOAP request. How can I make this possible?

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.com">
   <soapenv:Header/>
   <soapenv:Body>
      <ws:isValid>
         <token>$token</token>
      </ws:isValid>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

答:
Easy, use embedded expressions in the #(foo) form, they work for XML as well:

```<code>* def token = 'foo'
* def payload =
"""
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.com">
   <soapenv:Header/>
   <soapenv:Body>
      <ws:isValid>
         <token>#(token)</token>
      </ws:isValid>
   </soapenv:Body>
</soapenv:Envelope>
"""
* print payload
</code>```

Which prints:

```<code>[print] <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.com">
  <soapenv:Header/>
  <soapenv:Body>
    <ws:isValid>
      <token>foo</token>
    </ws:isValid>
  </soapenv:Body>
</soapenv:Envelope>
</code>```

I suggest you also refer to this set of examples, specifically for XML that will give you more ideas: xml.feature

Title: Karate API pass def variable in XML

Body:
I defined a variable with

* def token = '1bce02b8..'

I would like to retrieve the variable I defined so I can pass this to my SOAP request. How can I make this possible?

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.com">
   <soapenv:Header/>
   <soapenv:Body>
      <ws:isValid>
         <token>$token</token>
      </ws:isValid>
   </soapenv:Body>
</soapenv:Envelope>

Body:
Easy, use embedded expressions in the #(foo) form, they work for XML as well:

* def token = 'foo'
* def payload =
"""
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.com">
   <soapenv:Header/>
   <soapenv:Body>
      <ws:isValid>
         <token>#(token)</token>
      </ws:isValid>
   </soapenv:Body>
</soapenv:Envelope>
"""
* print payload

Which prints:

[print] <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.com">
  <soapenv:Header/>
  <soapenv:Body>
    <ws:isValid>
      <token>foo</token>
    </ws:isValid>
  </soapenv:Body>
</soapenv:Envelope>

I suggest you also refer to this set of examples, specifically for XML that will give you more ideas: xml.feature


问:
How to change default name of OpenID Connect middleware (nonce and correlation) cookies
I'm using the two ASP.NET Core middlewares for OpenID Connect and cookie authentication like below:

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "cookie",
    CookieName = "clientcookiename",
    CookieHttpOnly = true,
    CookieSecure = _hostingEnvironment.IsDevelopment() ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always,
    AutomaticAuthenticate = true,
    AutomaticChallenge = false,
    ExpireTimeSpan = TimeSpan.FromMinutes(60)
});

var oidcOptions = new OpenIdConnectOptions
{
    AuthenticationScheme = "oidc",
    SignInScheme = "cookie",
    ...
};
app.UseOpenIdConnectAuthentication(oidcOptions);
</code>```

During login in the web application this results in some default cookies related to nonce and correlation which look like this (exported from my browser developer tools):

```<code>{
    "domain": "localhost",
    "expirationDate": 1478762475.872038,
    "hostOnly": true,
    "httpOnly": true,
    "name": ".AspNetCore.OpenIdConnect.Nonce.CfDJ...ihRRfQid0Rw",
    "path": "/",
    "sameSite": "no_restriction",
    "secure": false,
    "session": false,
    "storeId": "0",
    "value": "N",
    "id": 1
  },
  {
    "domain": "localhost",
    "expirationDate": 1478762474.872093,
    "hostOnly": true,
    "httpOnly": true,
    "name": ".AspNetCore.Correlation.oidc.Apx...XlCFhuc...Hcq8",
    "path": "/",
    "sameSite": "no_restriction",
    "secure": false,
    "session": false,
    "storeId": "0",
    "value": "N",
    "id": 2
  }
</code>```

What are the responsibility of these cookies?

How do we change the CookieName of these cookies?

Will changing CookieName of these cookies have any consequences in some other place?

答:
This have been implemented

oidcOptions.NonceCookie = new CookieBuilder()
{
    Name = "TheNonceCookieName"
};

Body:
I'm using the two ASP.NET Core middlewares for OpenID Connect and cookie authentication like below:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "cookie",
    CookieName = "clientcookiename",
    CookieHttpOnly = true,
    CookieSecure = _hostingEnvironment.IsDevelopment() ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always,
    AutomaticAuthenticate = true,
    AutomaticChallenge = false,
    ExpireTimeSpan = TimeSpan.FromMinutes(60)
});

var oidcOptions = new OpenIdConnectOptions
{
    AuthenticationScheme = "oidc",
    SignInScheme = "cookie",
    ...
};
app.UseOpenIdConnectAuthentication(oidcOptions);

During login in the web application this results in some default cookies related to nonce and correlation which look like this (exported from my browser developer tools):

{
    "domain": "localhost",
    "expirationDate": 1478762475.872038,
    "hostOnly": true,
    "httpOnly": true,
    "name": ".AspNetCore.OpenIdConnect.Nonce.CfDJ...ihRRfQid0Rw",
    "path": "/",
    "sameSite": "no_restriction",
    "secure": false,
    "session": false,
    "storeId": "0",
    "value": "N",
    "id": 1
  },
  {
    "domain": "localhost",
    "expirationDate": 1478762474.872093,
    "hostOnly": true,
    "httpOnly": true,
    "name": ".AspNetCore.Correlation.oidc.Apx...XlCFhuc...Hcq8",
    "path": "/",
    "sameSite": "no_restriction",
    "secure": false,
    "session": false,
    "storeId": "0",
    "value": "N",
    "id": 2
  }

What are the responsibility of these cookies?

How do we change the CookieName of these cookies?

Will changing CookieName of these cookies have any consequences in some other place?


问:
bootstrap 4 modal-header trying to get badge aligned on right
I'm trying to get the "Banana Score" badge to float right, but to no avail. Does anyone know if this is even possible in Bootstrap 4.

I've tried all sorts of variations around flex, the best I had was a hack using columns, but this looks worse than the example below.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"  crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Customer
            Banana Score  4

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

```

答:
You need first to make the title width:100% then use float :

#exampleModalLabel {
  width: 100%;
}

#test {
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">

        <h5 class="modal-title" id="exampleModalLabel">Customer
          <span id="test" class="badge badge-secondary">Banana Score  <span class="badge badge-light">4</span></span>
        </h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">

      </div>
      <div class="modal-footer">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div></code>```

Body:
You need first to make the title width:100% then use float :

#exampleModalLabel {
  width: 100%;
}

#test {
  float: right;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">

        <h5 class="modal-title" id="exampleModalLabel">Customer
          <span id="test" class="badge badge-secondary">Banana Score  <span class="badge badge-light">4</span></span>
        </h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

      </div>
      <div class="modal-footer">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>


问:
Cakephp: multiple levels of belongsto in model
In a model, is it possible to do multiple iterations of belongsTo?

Assuming 3 tables, alerts, schedules, tasks and the model is for alerts. I want to get at a field from tasks but I have to join through schedules.

```<code> alerts.schedule_id -> schedules.tasks_id -> tasks.name
</code>```

I tried this syntax:

```<code>var $belongsTo = array(
         'Schedule' => array(
             'className' => 'Schedule',
             'foreignKey' => 'schedule_id'
         ),
         'Task' => array(
             'className' => 'Task',
             'foreignKey' => 'task_id'
         ));
</code>```

But that just joins both Schedules and Tasks directly to Alerts (here's the sql that was generated:

```<code>LEFT JOIN `schedules` AS `Schedule` ON (`Alert`.`schedule_id` = `Schedule`.`id`) LEFT JOIN `tasks` AS `Task` ON (`Alert`.`task_id` = `Task`.`id`)
)
</code>```

答:
I ended up setting this property:

```<code>$this->Alert->recursive = 2;
</code>```

In the index() function of the alerts controller.

Then I didn't have to do a separate find and was able to reference the name field in the Tasks table in index.ctp like this:

```<code><td><?php echo $alert['Schedule']['Task']['name']; ?> </td>
</code>```

Body:
In a model, is it possible to do multiple iterations of belongsTo?

Assuming 3 tables, alerts, schedules, tasks and the model is for alerts. I want to get at a field from tasks but I have to join through schedules.

 alerts.schedule_id -> schedules.tasks_id -> tasks.name

I tried this syntax:

var $belongsTo = array(
         'Schedule' => array(
             'className' => 'Schedule',
             'foreignKey' => 'schedule_id'
         ),
         'Task' => array(
             'className' => 'Task',
             'foreignKey' => 'task_id'
         ));

But that just joins both Schedules and Tasks directly to Alerts (here's the sql that was generated:

LEFT JOIN `schedules` AS `Schedule` ON (`Alert`.`schedule_id` = `Schedule`.`id`) LEFT JOIN `tasks` AS `Task` ON (`Alert`.`task_id` = `Task`.`id`)
)

Body:
I ended up setting this property:

$this->Alert->recursive = 2;

In the index() function of the alerts controller.

Then I didn't have to do a separate find and was able to reference the name field in the Tasks table in index.ctp like this:

<td><?php echo $alert['Schedule']['Task']['name']; ?>&nbsp;</td>


问:
Call subclass constructor from parent in Java
so I'm learning about java inheritance and I just ran into a situation I don't know how to solve.

What I'm trying to do is to call a subclass constructor from the superclass. I don't know if this makes any sense, but I'll try to explain myself with an example.

```<code>public class Phone {
    private String brand;
    private int weight;

    public Phone(String brand, int weight) {
        this.brand = brand;
        this.weight = weight;
    }

    public Phone(String brand, int weight, String tech) {
        // Here it is where I'm stuck
        // Call SmartPhone constructor with all the parameters
    }
}
</code>```

```<code>public class SmartPhone extends Phone {
    private String tech;

    public SmartPhone(String Brand, int weight, String tech) {
        super(brand, weight);
        this.tech = tech;
    }
}
</code>```

Why would I want to do that?

I would like to be able to not have to deal with SmartPhone in the main.

I'd like to be able to do:

```<code>Phone nokia = new Phone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance
</code>```

答:
```<code>Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance
</code>```

this makes no sense. If you want a SmartPhone instance, you must call

```<code>Phone iphone = new SmartPhone("iPhone", 368, "4G");
</code>```

You cannot call a sub-class constructor from a super-class constructor.

If you want the type of the Phone to be determined by the passed parameters, you can use static factory methods:

```<code>public class PhoneFactory {

    public static Phone newPhone (String brand, int weight) {
        return new Phone(brand, weight);
    }

    public static Phone newPhone (String brand, int weight, String tech) {
        return new SmartPhone(brand, weight, tech);
    }
}

Phone nokia = PhoneFactory.newPhone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = PhoneFactory.newPhone("iPhone", 368, "4G"); // <- SmartPhone instance
</code>```

Body:
so I'm learning about java inheritance and I just ran into a situation I don't know how to solve.

What I'm trying to do is to call a subclass constructor from the superclass. I don't know if this makes any sense, but I'll try to explain myself with an example.

public class Phone {
    private String brand;
    private int weight;

    public Phone(String brand, int weight) {
        this.brand = brand;
        this.weight = weight;
    }

    public Phone(String brand, int weight, String tech) {
        // Here it is where I'm stuck
        // Call SmartPhone constructor with all the parameters
    }
}

public class SmartPhone extends Phone {
    private String tech;

    public SmartPhone(String Brand, int weight, String tech) {
        super(brand, weight);
        this.tech = tech;
    }
}

Why would I want to do that?

I would like to be able to not have to deal with SmartPhone in the main.

I'd like to be able to do:

Phone nokia = new Phone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance

Body:
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance

this makes no sense. If you want a SmartPhone instance, you must call

Phone iphone = new SmartPhone("iPhone", 368, "4G");

You cannot call a sub-class constructor from a super-class constructor.

If you want the type of the Phone to be determined by the passed parameters, you can use static factory methods:

public class PhoneFactory {

    public static Phone newPhone (String brand, int weight) {
        return new Phone(brand, weight);
    }

    public static Phone newPhone (String brand, int weight, String tech) {
        return new SmartPhone(brand, weight, tech);
    }
}

Phone nokia = PhoneFactory.newPhone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = PhoneFactory.newPhone("iPhone", 368, "4G"); // <- SmartPhone instance


问:
Read retry on Azure Table
I got error No connection could be made because the target machine actively refused it often, when read from Azure Table Storage, sometime on 80(http) sometime on 443(https)

I know I can setup retry for write by .SaveChangesWithRetries(), but how to apply retry on read?

btw, I read by code

```<code>DataServiceQuery<datatype> query = tableContext.CreateQuery<datatype>("table");
IQueryable<datatype> results= from q in query select q
</code>```

答:
Use Polly: https://github.com/App-vNext/Polly to implement a retry handler which intercepts the error types / codes / etc you wish to handle and retry them. Polly is recommended by MS themselves for certain services (see: https://learn.microsoft.com/en-us/azure/architecture/best-practices/retry-service-specific and https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly)
.. and i've found its fuild syntax to be a joy to use.
Here's an example of a Polly retry handler i created to handle StorageException from Azure Storage. It implements an Exponential backoff (https://github.com/App-vNext/Polly/wiki/Retry#exponential-backoff) strategy.

```<code>int retries = 0;
int maxRetryAttempts = 5;

var retryStorageExceptionPolicy = Policy
    .Handle<StorageException>()
    .WaitAndRetry(maxRetryAttempts, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
        onRetry: (exception, calculatedWaitDuration) =>
        {
            retries++;
            loggingService.LogWarning(exception,
                new Dictionary<string, string>
                {
                    {"Message", $"A StorageException occurred when trying to Execute Query With Retry. This exception has been caught and will be retried." },
                    {"Current Retry Count", retries.ToString() },
                    {"tableName", table.Name},
                    {"ExtendedErrorInformation.ErrorCode", (exception as StorageException)?.RequestInformation.ExtendedErrorInformation.ErrorCode },
                    {"ExtendedErrorInformation.ErrorMessage", (exception as StorageException)?.RequestInformation.ExtendedErrorInformation.ErrorMessage }
                });
        });

retryStorageExceptionPolicy
    .ExecuteAndCapture(() =>
    {
        // your method accessing Azure Storage here
    });
</code>```

If you want a method to build a list of Transient error codes for Http calls let me know.

Title: Read retry on Azure Table

Body:
I got error No connection could be made because the target machine actively refused it often, when read from Azure Table Storage, sometime on 80(http) sometime on 443(https)

I know I can setup retry for write by .SaveChangesWithRetries(), but how to apply retry on read?

btw, I read by code

DataServiceQuery<datatype> query = tableContext.CreateQuery<datatype>("table");
IQueryable<datatype> results= from q in query select q

Body:
Use Polly: https://github.com/App-vNext/Polly to implement a retry handler which intercepts the error types / codes / etc you wish to handle and retry them. Polly is recommended by MS themselves for certain services (see: https://learn.microsoft.com/en-us/azure/architecture/best-practices/retry-service-specific and https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly)
.. and i've found its fuild syntax to be a joy to use.
Here's an example of a Polly retry handler i created to handle StorageException from Azure Storage. It implements an Exponential backoff (https://github.com/App-vNext/Polly/wiki/Retry#exponential-backoff) strategy.

int retries = 0;
int maxRetryAttempts = 5;

var retryStorageExceptionPolicy = Policy
    .Handle<StorageException>()
    .WaitAndRetry(maxRetryAttempts, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
        onRetry: (exception, calculatedWaitDuration) =>
        {
            retries++;
            loggingService.LogWarning(exception,
                new Dictionary<string, string>
                {
                    {"Message", $"A StorageException occurred when trying to Execute Query With Retry. This exception has been caught and will be retried." },
                    {"Current Retry Count", retries.ToString() },
                    {"tableName", table.Name},
                    {"ExtendedErrorInformation.ErrorCode", (exception as StorageException)?.RequestInformation.ExtendedErrorInformation.ErrorCode },
                    {"ExtendedErrorInformation.ErrorMessage", (exception as StorageException)?.RequestInformation.ExtendedErrorInformation.ErrorMessage }
                });
        });

retryStorageExceptionPolicy
    .ExecuteAndCapture(() =>
    {
        // your method accessing Azure Storage here
    });

If you want a method to build a list of Transient error codes for Http calls let me know.


问:
How to do a specific action on the first iteration of a while loop in a bash script
I need to make a script do a specific action on first loop iteration.

```<code>for file in /path/to/files/*; do
    echo "${file}"
done
</code>```

I want this output:

```<code>First run: file1
file2
file3
file4
...
</code>```

答:
I got my own solution</p>

```<code>counter=1

for file in /path/to/files/*; do
    echo -e "$( if [ "${counter}" -eq "1" ]; then echo "First run: "; fi )${file}"

counter=$((counter +1))

done
</code>```

Body:
I need to make a script do a specific action on first loop iteration.

for file in /path/to/files/*; do
    echo "${file}"
done

I want this output:

First run: file1
file2
file3
file4
...

Body:
I got my own solution

counter=1

for file in /path/to/files/*; do
    echo -e "$( if [ "${counter}" -eq "1" ]; then echo "First run: "; fi )${file}"

counter=$((counter +1))

done


问:
SELECT column FROM 2 tables Then Output In New table In 2 column
Say there are 2 tables with:

```<code>no key ref to each other
different number of rows

table1:
id   item
a    Apple
b    Pear

table2
no   student
I    John
II   Sara
III  Pete
</code>```

Is it possible to combine:

```<code>SELECT item FROM table1
SELECT student FROM table2
</code>```

Then PHP output table3 like this?

```<code>table3
ITEM       Student
Apple      John
Pear       Sara
           Pete
</code>```

ITEM and Student are totally independent of each other. I just want to list them side by side. (Which means ITEM that same row with Pete will have no value).
Need some expert view. Thanks.

答:
try </p>

```<code>create table table3 as select item from table1;
alter table table3 add column student TEXT;
update table3 set student = (select student from table2);
</code>```

Body:
Say there are 2 tables with:

no key ref to each other
different number of rows

table1:
id   item
a    Apple
b    Pear

table2
no   student
I    John
II   Sara
III  Pete

Is it possible to combine:

SELECT item FROM table1
SELECT student FROM table2

Then PHP output table3 like this?

table3
ITEM       Student
Apple      John
Pear       Sara
           Pete

ITEM and Student are totally independent of each other. I just want to list them side by side. (Which means ITEM that same row with Pete will have no value).
Need some expert view. Thanks.

Body:
try

create table table3 as select item from table1;
alter table table3 add column student TEXT;
update table3 set student = (select student from table2);


问:
Resizing UITableViewCell when entering edit mode
I have a cell that I have designed in Interface Builder, and when I enter edit mode, it moves the whole cell to the right to make space for the delete icon, but it pushes all items to the right, not shrink them down.  It pushes a UILabel off of the edge of the cell.  Also, this is over the move handles.  How do I shrink these items down, instead of just moving them.</p>

答:
I have a partial solution.
On the custom cell object I've created a IBOutlet to the view that holds all subviews in the cell (myContentView).
This way I can run this code to shrink it:

```<code>OrderReviewCell * cell = (OrderReviewCell * )[reviewTable cellForRowAtIndexPath:indexPath];
CGRect frame = cell.myContentView.frame;
frame.size.width = 200;
cell.myContentView.frame = frame;
</code>```

I've figured that the best place to put this is in shouldIndentWhileEditingRowAtIndexPath but my problem is Where to put the code that returns the cell to its normal state?

Hope it helps and DO let me know when you find the right answer!
Gonso

Body:
I have a partial solution.
On the custom cell object I've created a IBOutlet to the view that holds all subviews in the cell (myContentView).
This way I can run this code to shrink it:

OrderReviewCell * cell = (OrderReviewCell * )[reviewTable cellForRowAtIndexPath:indexPath];
CGRect frame = cell.myContentView.frame;
frame.size.width = 200;
cell.myContentView.frame = frame;

I've figured that the best place to put this is in shouldIndentWhileEditingRowAtIndexPath but my problem is Where to put the code that returns the cell to its normal state?

Hope it helps and DO let me know when you find the right answer!
Gonso


问:
Select2 call function with select2-selecting in append data
I am using Select2 for the selection of options in a form.

capture-1

The form is dynamic, so new lines are added when I click on the add button.

capture-2

The problem I have is that the function works only on the initial line, and not on the secondary lines.

```<code>$('.select2').on("select2-selecting", function(e) {
       alert(“HELLO”);
});
</code>```

Any ideas? regards

答:
You need to add/re-enable the event handling everytime new select2 element is added to DOM.

Wrap it in a function and call it after you add row.

```<code>function initSelectEvent(){
    // reset the previous event handlers on existing selects
    $('.select2').off("select2-selecting")
    // enable again including the newly added
    $('.select2').on("select2-selecting", function(e) {
        // your code to handle selected item
   });
}

/// in your code that adds the new row

...
initSelectEvent()
</code>```

Body:
I am using Select2 for the selection of options in a form.

capture-1

The form is dynamic, so new lines are added when I click on the add button.

capture-2

The problem I have is that the function works only on the initial line, and not on the secondary lines.

$('.select2').on("select2-selecting", function(e) {
       alert(“HELLO”);
});

Any ideas? regards

Body:
You need to add/re-enable the event handling everytime new select2 element is added to DOM.

Wrap it in a function and call it after you add row.

function initSelectEvent(){
    // reset the previous event handlers on existing selects
    $('.select2').off("select2-selecting")
    // enable again including the newly added
    $('.select2').on("select2-selecting", function(e) {
        // your code to handle selected item
   });
}

/// in your code that adds the new row

...
initSelectEvent()


问:
Can't update field in existing document in pymongo
I'm trying to add a field in to an existing document with pymongo.

here is my code:

```<code>from pymongo import MongoClient

client = MongoClient()
db = client['profiles']
collection = db['collection']

def createFields():
    collection.update({'_id' : '547f21f450c19fca35de53cd'}, {'$set': {'new_field':1}})

createFields()
</code>```

when I enter the following in to the mongoDB interpreter

```<code>>use profiles
>db.collection.find()
</code>```

I can see that there have not been any fields added to the specified document.

答:
You should add db before your script

Just try this, it works fine for me

In Mongo CLI

```<code>> use profiles
> db.collection.insertOne({'_id': '547f21f450c19fca35de53cd'})
> db.collection.find()
{ "_id" : "547f21f450c19fca35de53cd" }
</code>```

Python Script -> test.py

```<code>from pymongo import MongoClient
client = MongoClient()
db = client['profiles']
collection = db['collection']

def createFields():
    db.collection.update({'_id' : '547f21f450c19fca35de53cd'}, {'$set': {'new_field':-881}})

createFields()
</code>```

Command Line

```<code>> python test.py
</code>```

Mongo CLI

```<code>> use profiles
> db.collection.find()
> { "_id" : "547f21f450c19fca35de53cd", "new_field" : -881 }
</code>```

For pymongo, use update_one or update_many instead of update

Body:
I'm trying to add a field in to an existing document with pymongo.

here is my code:

from pymongo import MongoClient

client = MongoClient()
db = client['profiles']
collection = db['collection']

def createFields():
    collection.update({'_id' : '547f21f450c19fca35de53cd'}, {'$set': {'new_field':1}})

createFields()

when I enter the following in to the mongoDB interpreter

>use profiles
>db.collection.find()

I can see that there have not been any fields added to the specified document.

Body:
You should add db before your script

Just try this, it works fine for me

In Mongo CLI

> use profiles
> db.collection.insertOne({'_id': '547f21f450c19fca35de53cd'})
> db.collection.find()
{ "_id" : "547f21f450c19fca35de53cd" }

Python Script -> test.py

from pymongo import MongoClient
client = MongoClient()
db = client['profiles']
collection = db['collection']

def createFields():
    db.collection.update({'_id' : '547f21f450c19fca35de53cd'}, {'$set': {'new_field':-881}})

createFields()

Command Line

> python test.py

Mongo CLI

> use profiles
> db.collection.find()
> { "_id" : "547f21f450c19fca35de53cd", "new_field" : -881 }

For pymongo, use update_one or update_many instead of update


问:
Treat try and except the same
I'm writing something that checks if a port is open, but modifying it to my use.

I set timeout for the check and if timeout reaches it raises socket.timeout exception, but I want a code block inside the try to also be invoked on socket.timeout:

```<code>try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(5)
    result = sock.connect_ex((check_server_ip, check_port))
    if result == 0:
        # act on open port
    else:
        # act on closed port
    sock.close()
except socket.timeout:
    # act on closed port
</code>```

The code block I have on # act on closed port is long. I can create a function that has the code and call it on the else statement and socket.timeout exception, but I bet python has something more clever.

What can achieve this?

答:
I don't think you need something clever or magical here. I looked at your code, then entered python -c "import this" in my terminal and saw this among the lines:

Flat is better than nested.

So, you don't need to create, set timeout and close a socket in the try ... except timeout - nothing throws timeout there:

```<code>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)

try:
    result = sock.connect_ex((check_server_ip, check_port))
    socket_connected = result == 0
except socket.timeout:
    socket_connected = False

if socket_connected:
    do_connected_stuff()
else:
    do_disconnected_stuff()

sock.close()
</code>```

However, the correctness of this code really depends on if do_connected_stuff() can throw socket.timeout and if do_disconnected_stuff() is a meaningful action in this case. If yes to all questions, then you've already got a pretty much optimal structure - at least without the full view of your system.

Title: Treat try and except the same

Body:
I'm writing something that checks if a port is open, but modifying it to my use.

I set timeout for the check and if timeout reaches it raises socket.timeout exception, but I want a code block inside the try to also be invoked on socket.timeout:

try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(5)
    result = sock.connect_ex((check_server_ip, check_port))
    if result == 0:
        # act on open port
    else:
        # act on closed port
    sock.close()
except socket.timeout:
    # act on closed port

The code block I have on # act on closed port is long. I can create a function that has the code and call it on the else statement and socket.timeout exception, but I bet python has something more clever.

What can achieve this?

Body:
I don't think you need something clever or magical here. I looked at your code, then entered python -c "import this" in my terminal and saw this among the lines:

Flat is better than nested.

So, you don't need to create, set timeout and close a socket in the try ... except timeout - nothing throws timeout there:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)

try:
    result = sock.connect_ex((check_server_ip, check_port))
    socket_connected = result == 0
except socket.timeout:
    socket_connected = False

if socket_connected:
    do_connected_stuff()
else:
    do_disconnected_stuff()

sock.close()

However, the correctness of this code really depends on if do_connected_stuff() can throw socket.timeout and if do_disconnected_stuff() is a meaningful action in this case. If yes to all questions, then you've already got a pretty much optimal structure - at least without the full view of your system.


问:
Check if emoji exist in a string [BASH]
I'm trying to figure out if an emoji is present in a string as a substring in Bash 4.3.11

emoji="[\uD800-\uDBFF]"
[[ "" =~ $emoji ]] && echo "Emoji found!"
```

This doesn't seem to work.

答:
try using pattern matching, encoding code points to utf-8 bytes:</p>

```<code>emoji=$'\xed[\xa0-\xaf][\x80-\xbf]'
[[ "..." = *$emoji* ]] && echo found
</code>```

Title: Check if emoji exist in a string [BASH]

Body:
I'm trying to figure out if an emoji is present in a string as a substring in Bash 4.3.11

emoji="[\uD800-\uDBFF]"
[[ "" =~ $emoji ]] && echo "Emoji found!"

This doesn't seem to work.

Body:
try using pattern matching, encoding code points to utf-8 bytes:

emoji=$'\xed[\xa0-\xaf][\x80-\xbf]'
[[ "..." = *$emoji* ]] && echo found