Calling PowerShell Get-SPContentDatabase in C# - powershell

I am trying to use the Get-SPContentDatabase powershell command from a code behind file:
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("Get-SPContentDatabase -site http:////gBox.contoso.com");
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
if (PSOutput.Count > 0)
{
foreach (PSObject outputItem in PSOutput)
{
if (outputItem != null)
{
lblResults.Text += outputItem.BaseObject.ToString();
lblResults.Text += outputItem.BaseObject.GetType().FullName;
lblResults.Text += "<hr>";
}
}
}
else
{
lblResults.Text = "No output found";
}
}
However, the PSOutput keeps coming back with zero objects.
The Command works great from the PowerShell window, but not from the code behind.
Any thoughts?

The command Get-SPContentDatabase is failed to execute since Microsoft.SharePoint.PowerShell module have to be loaded first:
using (var psInst = PowerShell.Create())
{
psInst.AddScript("Add-PsSnapin Microsoft.SharePoint.PowerShell");
}
Example: print ContentDb names
using (var psInst = PowerShell.Create())
{
psInst.AddScript("Add-PsSnapin Microsoft.SharePoint.PowerShell");
psInst.AddScript("Get-SPContentDatabase -site http://contoso.intranet.com/");
var result = psInst.Invoke();
foreach (var outputItem in result)
{
var contentDb = outputItem.BaseObject as SPContentDatabase;
Console.WriteLine(contentDb.Name);
}
}

Related

a function is giving me an error about a comma

function emptyInputSignup($fname, $lname, $email, $username, $pwd, $pwdrepeat) {
$result = null;
if (empty($fname) || empty($lname) || empty($email) || empty($username) || empty($pwd) || empty($pwdrepeat)) {
$result = true;
} else {
$result = false;
}
return $result;
};
function invalidUid($username) {
$result = null;
if (!preg_match('/^[a-zA-Z0-9]*$/'), $username) {
$result = true;
} else {
$result = false;
}
return $result;
}
What have I donr wrong, what does it want, i literally copied the emptyInputSignup function and then wrote some regex in and vscode is confused
I've stared at it for an hour, when I google for regex not working properly, I couldn't find anyone having similar problems.
You need to put , $username inside the preg_match function parenthesis, after the regex pattern. It is in the wrong place.
It should be:
if (!preg_match('/^[a-zA-Z0-9]*$/', $username)) {
$result = true;
} else {
$result = false;
}

Why I'm getting the error: "Parameter 1 to Credis_Client::scan() expected to be a reference"?

I'm trying to call this class function:
public function scan(&$Iterator, $pattern = null, $count = null)
{
return $this->__call('scan', array(&$Iterator, $pattern, $count));
}
From my class:
$itScan = NULL;
while($arr_keys = $this->redisClient->scan($itScan, '', 10000)) {
foreach($arr_keys as $str_key) {
echo "Here is a key: $str_key\n";
}
}
I understand this is something related to the & pointer but I can't figure who to call it from inside my class.
Thank you!
This is the proper way to iterate over your results :
$i = null;
$allResults = [];
do {
$someResults = $redis->scan($i, "*", 10000);
if (!empty($someResults)) {
$allKeys = array_merge($allKeys, $someResults);
}
}
while ($i);

MP3 TagLib search and copy issue

Greetings to all of you.
My problem is:
I need to search through user selected folder that contains MP3 files and check which file(s) has or contains specified tag. If it does, i will copy it to specified folder. I have managed to do something, but only partially, cause for example, i manage to copy genre "Pop" files, but not "Blues" files.
Getting contains to work is a total nightmare, cant get it to work at all.
Code:
try
{
FolderBrowserDialog folder = new FolderBrowserDialog();
DialogResult result = folder.ShowDialog();
string genre = "Blues";
var matchingFiles = Directory.GetFiles(folder.SelectedPath, "*.mp3", SearchOption.AllDirectories).Where(x =>
{
var f = TagLib.File.Create(x);
return (((TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2)).JoinedGenres == genre);
});
foreach (string f in matchingFiles)
{
System.IO.File.Copy(f, Path.Combine(#"destinationFolder", new FileInfo(f).Name));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Any help is welcome.
Problem solved:
try
{
FolderBrowserDialog folder = new FolderBrowserDialog();
DialogResult result = folder.ShowDialog();
string upit = search.Text;
var matchingFiles = Directory.GetFiles(folder.SelectedPath, "*.mp3", SearchOption.AllDirectories).Where(x =>
{
var f = TagLib.File.Create(x);
return (((TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2)).Comment != null && ((TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2)).Comment.Contains(upit));
}
);
foreach (string f in matchingFiles)
{
System.IO.File.Copy(f, Path.Combine(path, new FileInfo(f).Name));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
}

How can I programmatically create nested where clauses with Zend\Db\Sql component?

I've tried using the following code to accomplish it, but the unnest function returns an error:
foreach($params as $key=>$param) {
if(strpos($param, ',') !== false) {
$where = new \Zend\Db\Sql\Where();
$where->nest();
$param_arr = explode(',', $param);
$entered_once = 0;
foreach($param_arr as $p) {
$where->equalTo($key, $p);
if($entered_once < count($param_arr)) {
$where->or;
}
$entered_once++;
}
$where->unnest();
$select->where($where);
}
else {
$select->where(array($key => $param));
}
}
I've figured out what I'm doing wrong: I didn't realize that the nest() function returned a brand new PredicateSet and that's what I needed to call everything on. The solution is as follows:
foreach($params as $key=>$param) {
if(strpos($param, ',') !== false) {
$where = new \Zend\Db\Sql\Where();
$predicate_set = $where->nest();
$param_arr = explode(',', $param);
$entered_once = 0;
foreach($param_arr as $p) {
$predicate_set->equalTo($key, $p);
if($entered_once < count($param_arr)) {
$predicate_set->or;
}
$entered_once++;
}
$predicate_set->unnest();
$select->where($where);
}
else {
$select->where(array($key => $param));
}
}

Entity Framework POCO entity template : format property names

properties in the database are all in small case and use underscore for word separation. E.g.:
customer_order_id
I want the property names to conform to my PropertyNameCodingConvention, i.e.: customer_order_id -> CustomerOrderId
I have changed the T4 template to accomplish that but I am curious if there is a solution already available.
In EDMX file, you have two different schema, and one mapping schema. What you can do is, you can modify conceptual schema and change property names, however refreshing EDMX might erase this information. But by doing this, you will not have to change template at all.
This requires change to the template, but here is how I did it:
Add to the end of EntityPoco.tt (right before last closing '#>' tag):
private string N(string input) {
return System.Text.RegularExpressions.Regex.Replace(input,
"(?:_|^)([a-z])",
match => match.Groups[1].Value.ToUpper()).Replace("_", "");
}
Wrap all the places where a property name is being output (6 total, see code below).
Here is a complete text:
<#
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#>
<## template language="C#" debug="false" hostspecific="true"#>
<## include file="EF.Utility.CS.ttinclude"#><##
output extension=".cs"#><#
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
CodeRegion region = new CodeRegion(this, 1);
MetadataTools ef = new MetadataTools(this);
string inputFile = #"PSI.Entities.edmx";
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
string namespaceName = code.VsNamespaceSuggestion();
EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
WriteHeader(fileManager);
foreach (var entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
fileManager.StartNewFile(entity.Name + ".cs");
BeginNamespace(namespaceName, code);
#>
<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#><#=code.StringBefore(" : ", code.Escape(entity.BaseType))#>
{
<#
var propertiesWithDefaultValues = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity && p.DefaultValue != null);
var collectionNavigationProperties = entity.NavigationProperties.Where(np => np.DeclaringType == entity && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
var complexProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == entity);
if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any())
{
#>
public <#=code.Escape(entity)#>()
{
<#
foreach (var edmProperty in propertiesWithDefaultValues)
{
#>
this.<#=N(code.Escape(edmProperty))#> = <#=code.CreateLiteral(edmProperty.DefaultValue)#>;
<#
}
foreach (var navigationProperty in collectionNavigationProperties)
{
#>
this.<#=N(code.Escape(navigationProperty))#> = new HashSet<<#=code.Escape(navigationProperty.ToEndMember.GetEntityType())#>>();
<#
}
foreach (var complexProperty in complexProperties)
{
#>
this.<#=N(code.Escape(complexProperty))#> = new <#=code.Escape(complexProperty.TypeUsage)#>();
<#
}
#>
}
<#
}
var primitiveProperties = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity);
if (primitiveProperties.Any())
{
foreach (var edmProperty in primitiveProperties)
{
WriteProperty(code, edmProperty);
}
}
if (complexProperties.Any())
{
#>
<#
foreach(var complexProperty in complexProperties)
{
WriteProperty(code, complexProperty);
}
}
var navigationProperties = entity.NavigationProperties.Where(np => np.DeclaringType == entity);
if (navigationProperties.Any())
{
#>
<#
foreach (var navigationProperty in navigationProperties)
{
WriteNavigationProperty(code, navigationProperty);
}
}
#>
}
<#
EndNamespace(namespaceName);
}
foreach (var complex in ItemCollection.GetItems<ComplexType>().OrderBy(e => e.Name))
{
fileManager.StartNewFile(complex.Name + ".cs");
BeginNamespace(namespaceName, code);
#>
<#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#>
{
<#
var complexProperties = complex.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == complex);
var propertiesWithDefaultValues = complex.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == complex && p.DefaultValue != null);
if (propertiesWithDefaultValues.Any() || complexProperties.Any())
{
#>
public <#=code.Escape(complex)#>()
{
<#
foreach (var edmProperty in propertiesWithDefaultValues)
{
#>
this.<#=N(code.Escape(edmProperty))#> = <#=code.CreateLiteral(edmProperty.DefaultValue)#>;
<#
}
foreach (var complexProperty in complexProperties)
{
#>
this.<#=N(code.Escape(complexProperty))#> = new <#=code.Escape(complexProperty.TypeUsage)#>();
<#
}
#>
}
<#
}
var primitiveProperties = complex.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == complex);
if (primitiveProperties.Any())
{
foreach(var edmProperty in primitiveProperties)
{
WriteProperty(code, edmProperty);
}
}
if (complexProperties.Any())
{
#>
<#
foreach(var edmProperty in complexProperties)
{
WriteProperty(code, edmProperty);
}
}
#>
}
<#
EndNamespace(namespaceName);
}
if (!VerifyTypesAreCaseInsensitiveUnique(ItemCollection))
{
return "";
}
fileManager.Process();
#>
<#+
void WriteHeader(EntityFrameworkTemplateFileManager fileManager)
{
fileManager.StartHeader();
#>
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
<#+
fileManager.EndBlock();
}
void BeginNamespace(string namespaceName, CodeGenerationTools code)
{
CodeRegion region = new CodeRegion(this);
if (!String.IsNullOrEmpty(namespaceName))
{
#>
namespace <#=code.EscapeNamespace(namespaceName)#>
{
<#+
PushIndent(CodeRegion.GetIndent(1));
}
}
void EndNamespace(string namespaceName)
{
if (!String.IsNullOrEmpty(namespaceName))
{
PopIndent();
#>
}
<#+
}
}
void WriteProperty(CodeGenerationTools code, EdmProperty edmProperty)
{
WriteProperty(Accessibility.ForProperty(edmProperty),
code.Escape(edmProperty.TypeUsage),
code.Escape(edmProperty),
code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
code.SpaceAfter(Accessibility.ForSetter(edmProperty)));
}
void WriteNavigationProperty(CodeGenerationTools code, NavigationProperty navigationProperty)
{
var endType = code.Escape(navigationProperty.ToEndMember.GetEntityType());
WriteProperty(PropertyVirtualModifier(Accessibility.ForProperty(navigationProperty)),
navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
code.Escape(navigationProperty),
code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
code.SpaceAfter(Accessibility.ForSetter(navigationProperty)));
}
void WriteProperty(string accessibility, string type, string name, string getterAccessibility, string setterAccessibility)
{
#>
<#=accessibility#> <#=type#> <#=N(name)#> { <#=getterAccessibility#>get; <#=setterAccessibility#>set; }
<#+
}
string PropertyVirtualModifier(string accessibility)
{
return accessibility + (accessibility != "private" ? " virtual" : "");
}
bool VerifyTypesAreCaseInsensitiveUnique(EdmItemCollection itemCollection)
{
var alreadySeen = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
foreach(var type in itemCollection.GetItems<StructuralType>())
{
if (!(type is EntityType || type is ComplexType))
{
continue;
}
if (alreadySeen.ContainsKey(type.FullName))
{
Error(String.Format(CultureInfo.CurrentCulture, "This template does not support types that differ only by case, the types {0} are not supported", type.FullName));
return false;
}
else
{
alreadySeen.Add(type.FullName, true);
}
}
return true;
}
private string N(string input) {
return System.Text.RegularExpressions.Regex.Replace(input, "(?:_|^)([a-z])", match => match.Groups[1].Value.ToUpper()).Replace("_", "");
}
#>