How to add Mock db tables in C# test cases - .net-core

How to create mock db tables for the separate class file in test cases to access the service test case and also I need for that tables between parent and child relation
public static class MockTestData
{
// Test data for the DbSet<User> getter
public static IQueryable<EaepTieriiLangComp> Langcomps
{
get
{ return new List<EaepTieriiLangComp>
{
new EaepTieriiLangComp{EaepAssessmentId=1,LangCompId=1,IsPrimary ="Y",LangId =1,LangReadId=1,LangWrittenId=1,LangSpokenId=1,LangUnderstandId=1 },
new EaepTieriiLangComp{EaepAssessmentId=2,LangCompId=1 ,IsPrimary ="N",LangId =2,LangReadId=2,LangWrittenId=2,LangSpokenId=2,LangUnderstandId=2 }//Lang =obj,LangRead=objRead,LangSpoken =objSpeak,LangWritten=objWrite,LangUnderstand=objUnderstand
}.AsQueryable();
}
}
public static IQueryable<LookupLang> LookupLangs
{
get
{ return new List<LookupLang>
{
new LookupLang{LangId = 1,Description = "lang1",IsActive="Y"},
new LookupLang{LangId = 2,Description = "lang2",IsActive="N"}
}.AsQueryable();
}
}
}`
enter code here`
I tried for the above flow but i didnot get relatons for that tables

If you are using EF Core, you can create inmemory database, add data and make query to it.
Here is example:
First you need install Microsoft.EntityFrameworkCore.InMemory package. After this make options:
_options = new DbContextOptionsBuilder<SomeDbContext>()
.UseInMemoryDatabase(databaseName: "DbTest")
.Options;
using var context = new SomeDbContext(_options);
context.Database.EnsureCreated();
Then add your data:
context.AddRange(
new LookupLang{LangId = 1,Description = "lang1",IsActive="Y"},
new LookupLang{LangId = 2,Description = "lang2",IsActive="N"}
)
And now you can use context for testing purposes

Thank you so much advise to use EF core.InMemory package it is working fine now I followed below code
Inmemory class
using Assessments.TierIIQueryDataModel;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace AssessmentCommandTest.Helpers
{
public class InMemoryDataProviderQueryService : IDisposable
{
private bool disposedValue = false; // To detect redundant calls
public DbQueryContext CreateContextForInMemory()
{
var option = new DbContextOptionsBuilder<DbQueryContext>().UseInMemoryDatabase(databaseName: "Test_QueryDatabase").Options;
var context = new DbQueryContext(option);
if (context != null)
{
//context.Database.EnsureDeleted();
context.Database.EnsureCreated();
}
return context;
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
}
and access to DbQueryContext conext file in my code and write mock tables as below
using AssessmentCommandTest.Helpers;
using Assessments.TierIIQueryDataModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AssessmentCommandTest.MockDbTables
{
public class MockQueryDbContext
{
public TierIIQueryContext MockTierIIQueryContexts()
{
//Create object for Inmemory DB provider
var factory = new InMemoryDataProviderQueryService();
//Get the instance of TierIIQueryContext
var context = factory.CreateContextForInMemory();
context.LookupLang.Add(new LookupLang { LangId = 1, Description = "Arabic", IsActive = "Y" });
context.LookupLang.Add(new LookupLang { LangId = 2, Description = "Bangali", IsActive = "Y" });
context.LookupLang.Add(new LookupLang { LangId = 3, Description = "English", IsActive = "Y" });
context.LookupLang.Add(new LookupLang { LangId = 4, Description = "French", IsActive = "Y" });
enter code here
context.SaveChanges();
return context;
}
}
}

Related

Add bluetooth-lowenergy services and writable characteristics to smartephone Xamarin

I am developing a mobile application that use bluetooth-lowenergy, i need to create services and characteristics in the application
Thanks
this after two days of search, and by reading this page BLE Android i solved my problem
here the class used to create services
using System;
using Android.App;
using Android.Bluetooth;
using Android.Bluetooth.LE;
using Android.OS;
using Java.Util;
using SitBle.Droid;
using SitBle.Interfaces;
using Exception = System.Exception;
[assembly: Xamarin.Forms.Dependency(typeof(Advertiser))]
namespace SitBle.Droid
{
public class Advertiser : IAdvertiser
{
private BluetoothAdvertiseCallback _advertiseCallback;
private readonly UUID _serviceUuid = UUID.FromString("795090c7-420d-4048-a24e-18e60180e23c");
private readonly UUID _characteristicCounterUuid = UUID.FromString("31517c58-66bf-470c-b662-e352a6c80cba");
private readonly UUID _characteristicInteractorUuid = UUID.FromString("0b89d2d4-0ea6-4141-86bb-0c5fb91ab14a");
private readonly UUID _descriptorConfigUuid = UUID.FromString("00002902-0000-1000-8000-00805f9b34fb");
public void Advertise()
{
try
{
_advertiseCallback = new BluetoothAdvertiseCallback();
var androidBluetoothGattServerCallback = new AndroidBluetoothGattServerCallback();
var adapter = BluetoothAdapter.DefaultAdapter;
var advertiseSettingBuilder = new AdvertiseSettings.Builder()
.SetAdvertiseMode(AdvertiseMode.Balanced).SetConnectable(true).SetTimeout(0)
.SetTxPowerLevel(AdvertiseTx.PowerMedium);
var advertiseSetting = advertiseSettingBuilder.Build();
var adverisingDataBuilder = new AdvertiseData.Builder().SetIncludeDeviceName(false).AddServiceUuid(new ParcelUuid(_serviceUuid));
adapter.BluetoothLeAdvertiser.StartAdvertising(advertiseSetting, adverisingDataBuilder.Build(), _advertiseCallback);
var appContext = Application.Context;
var mBluetoothManager = (BluetoothManager)appContext.GetSystemService("bluetooth");
var mGattServer = mBluetoothManager.OpenGattServer(appContext, androidBluetoothGattServerCallback);
mGattServer.AddService(CreateService());
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private BluetoothGattService CreateService()
{
BluetoothGattService service = new BluetoothGattService(_serviceUuid, GattServiceType.Primary);
// Counter characteristic (read-only, supports subscriptions)
BluetoothGattCharacteristic counter = new BluetoothGattCharacteristic(_characteristicCounterUuid,GattProperty.Read|GattProperty.Notify,GattPermission.Read);
BluetoothGattDescriptor counterConfig = new BluetoothGattDescriptor(_descriptorConfigUuid, GattDescriptorPermission.Read|GattDescriptorPermission.Write);
counter.AddDescriptor(counterConfig);
// Interactor characteristic
BluetoothGattCharacteristic interactor = new BluetoothGattCharacteristic(_characteristicInteractorUuid, GattProperty.Read|GattProperty.Write|GattProperty.Notify, GattPermission.Write);
service.AddCharacteristic(counter);
service.AddCharacteristic(interactor);
return service;
}
}
public class BluetoothAdvertiseCallback : AdvertiseCallback
{
public BluetoothAdvertiseCallback()
{
}
public override void OnStartSuccess(AdvertiseSettings settingsInEffect)
{
Console.WriteLine("Success");
}
public override void OnStartFailure(AdvertiseFailure errorCode)
{
Console.WriteLine("Fail");
}
}
public class AndroidBluetoothGattServerCallback : BluetoothGattServerCallback
{
public AndroidBluetoothGattServerCallback()
{
}
}
}

Unit Test IdentityDbContext

I´ve read that the new EF7 allows in memory storage that makes easier the unit testing. This works great on a DbContext, but the problem that I have so far is that I'm using a IdentityDbContext, which doesn´t come with that option, or I haven't found it so far.
What I'm trying to do is to add unit test to my AccountController which depends on the new UserManager and SignInManager classes. I would like to test against an In-Memory list but I still don´t know how to make those clases use a dbcontext different than the EF-SQL IdentityDbContext. Is there any way around this?
Dec. 27th 2015 - Update for RC1
The project.json
{
"version": "1.0.0-*",
"dependencies": {
"{assembly under test}": "",
"Microsoft.AspNet.Hosting": "1.0.0-*",
"xunit": "2.1.0",
"xunit.runner.dnx": "2.1.0-rc1-*"
},
"commands": {
"test": "xunit.runner.dnx"
},
"frameworks": {
"dnx451": {
"dependencies": {
"Moq": "4.2.1312.1622"
}
}
}
}
A test class sample to test AccountController:
using {Your NS}.Controllers;
using Microsoft.AspNet.Identity;
using Moq;
using Xunit;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.OptionsModel;
using System.Threading;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.ModelBinding;
using System.Collections.Generic;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.Extensions.Logging;
namespace NS.test.Controllers
{
public class TestRole
{
public string Id { get; private set; }
public string Name { get; set; }
}
public interface ITestUserStore<T>:IUserStore<T>, IUserPasswordStore<T> where T :class
{ }
public class AccountControllerTest
{
private static UserManager<TUser> GetUserManager<TUser>(List<IUserValidator<TUser>> userValidators) where TUser : class
{
var store = new Mock<ITestUserStore<TUser>>();
store.Setup(s => s.CreateAsync(It.IsAny<TUser>(), It.IsAny<CancellationToken>())).ReturnsAsync(IdentityResult.Success);
var options = new Mock<IOptions<IdentityOptions>>();
var idOptions = new IdentityOptions();
idOptions.Lockout.AllowedForNewUsers = false;
options.Setup(o => o.Value).Returns(idOptions);
var pwdValidators = new List<PasswordValidator<TUser>>();
pwdValidators.Add(new PasswordValidator<TUser>());
var userManager = new UserManager<TUser>(store.Object, options.Object, new PasswordHasher<TUser>(),
userValidators, pwdValidators, new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(), null,
new Mock<ILogger<UserManager<TUser>>>().Object,
null);
return userManager;
}
private static Mock<SignInManager<TUser>> MockSigninManager<TUser>(UserManager<TUser> userManager) where TUser : class
{
var context = new Mock<HttpContext>();
var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
var roleManager = new RoleManager<TestRole>(new Mock<IRoleStore<TestRole>>().Object,new RoleValidator<TestRole>[] { new RoleValidator<TestRole>() }, null, null, null, null);
var identityOptions = new IdentityOptions();
var options = new Mock<IOptions<IdentityOptions>>();
options.Setup(a => a.Value).Returns(identityOptions);
var claimsFactory = new UserClaimsPrincipalFactory<TUser, TestRole>(userManager, roleManager, options.Object);
return new Mock<SignInManager<TUser>>(userManager, contextAccessor.Object, claimsFactory, options.Object, null);
}
[Fact]
public async Task RegisterTest()
{
var userValidators = new List<IUserValidator<YourUser>>();
var validator = new Mock<IUserValidator<YourUser>>();
userValidators.Add(validator.Object);
var userManager = GetUserManager(userValidators);
validator.Setup(v => v.ValidateAsync(userManager, It.IsAny<ChatLeUser>()))
.Returns(Task.FromResult(IdentityResult.Success)).Verifiable();
var signinManager = MockSigninManager<YourUser>(userManager);
signinManager.Setup(m => m.SignInAsync(It.IsAny<YourUser>(), It.IsAny<bool>(), null)).Returns(Task.FromResult(0)).Verifiable();
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
using (var controller = new AccountController(userManager, signinManager.Object) { ViewData = viewData })
{
var result = await controller.Register(new RegisterViewModel()
{
ConfirmPassword = "test123",
Password = "Test123-123",
UserName = "test"
});
Assert.IsType<RedirectToActionResult>(result);
}
}
}
}
Ultimately, you'll probably want to mock the UserManager and SignInManager directly. Unfortunately, many of those methods under beta-3 aren't virtual; you'll be a bit stuck there. However, you can see from the source of UserManager and SignInManager that the Identity team appears to be addressing those for the next release.
I personally have several tests not compiling because of the same issue.

e.GetListSourceFieldValue returns null in the CustomUnboundColumnData event handler

I am using DevExpress control within an ASP.NET MVC 4 project.
I am using unbound columns in the GridView extension for ASP.NET MVC. In the CustomUnboundColumnData event handler, the e.GetListSourceFieldValue always returns null for me.
I then tried getting the value directly from the model instead of calling this method (please see the commented line just above the call to the method) but even though that worked, it had side-effects, which I won't get into just now.
I am using ASP.NET MVC 4 with Visual Web Developer Express 2010 edition. I am using DevExpress extensions for MVC v12.2.10.0.
My OS is Windows 7, 64-bit. However, the extensions I am using are 32-bit only.
I cannot ship my whole solution as it is broken down into multiple projects, most of which have lots of IP code I've written for my client. But here are the relevant pieces from my code.
Index.cshtml (Razor View Engine)
-------------------------------------------------------------------
#model List<GlobalizationUI.Presentation.ViewModels.StringTableRow>
#{
ViewBag.Title = "Strings";
}
<div id = "pageCaption">Strings</div>
#Html.Partial("_StringsPartial", Model)
_StringsPartial.cshtml (Razor View Engine)
-------------------------------------------------------------------
#using System.Web.UI.WebControls;
#using System.Data;
#model List<GlobalizationUI.Presentation.ViewModels.StringTableRow>
#Html.DevExpress().GridView(settings =>
{
settings.Name = "gvStrings";
settings.CallbackRouteValues = new { Controller = "Strings", Action = "StringsPartial" };
settings.Width = 1200;
settings.SettingsPager.Position = PagerPosition.TopAndBottom;
settings.SettingsPager.FirstPageButton.Visible = true;
settings.SettingsPager.LastPageButton.Visible = true;
settings.SettingsPager.PageSizeItemSettings.Visible = true;
settings.SettingsPager.PageSizeItemSettings.Items = new string[] { "10", "20", "50", "100", "200" };
settings.SettingsPager.PageSize = 50;
settings.Settings.ShowFilterRow = true;
settings.Settings.ShowFilterRowMenu = true;
settings.CommandColumn.Visible = true;
settings.CommandColumn.ClearFilterButton.Visible = true;
settings.Settings.ShowHeaderFilterButton = true;
settings.KeyFieldName = "ResourceKeyId";
settings.Columns.Add("Key");
var categoryColumn = settings.Columns.Add("CategoryId", "Category");
categoryColumn.ColumnType = MVCxGridViewColumnType.ComboBox;
var categoryColumnEditProperties = categoryColumn.PropertiesEdit as ComboBoxProperties;
categoryColumnEditProperties.DataSource = ViewBag.AllCategories;
categoryColumnEditProperties.TextField = "Name";
categoryColumnEditProperties.ValueField = "Id";
categoryColumnEditProperties.ValueType = typeof(long);
if (Model != null && Model.Count > 0 &&
Model[0] != null && Model[0].StringValues != null && Model[0].StringValues.Count > 0)
{
foreach (var kvp in Model[0].StringValues)
{
settings.Columns.Add(col =>
{
col.FieldName = kvp.CultureShortName;
col.Caption = kvp.CultureShortName;
col.UnboundType = DevExpress.Data.UnboundColumnType.Object;
col.SetDataItemTemplateContent(container => { ViewContext.Writer.Write(DataBinder.Eval(container.DataItem, col.FieldName + ".StringValue")); });
col.SetEditItemTemplateContent(container =>
{
Html.DevExpress().TextBox(s =>
{
s.Name = string.Format("txt{0}", kvp.CultureShortName);
}).Bind(kvp.StringValue).Render();
});
});
}
}
settings.CustomUnboundColumnData = (sender, e) =>
{
var fixedColumns = new List<string> { "ResourceKeyId", "Key", "CategoryId" };
if (!fixedColumns.Contains(e.Column.FieldName))
{
if (e.IsGetData)
{
try
{
// var values = Model[e.ListSourceRowIndex].StringValues;
var values = e.GetListSourceFieldValue(e.ListSourceRowIndex, "StringValues") as IList<GlobalizationUI.Presentation.ViewModels.CultureNameAndStringValue>;
if (values != null)
{
var value = values.FirstOrDefault(pair => pair.CultureShortName == e.Column.FieldName);
var defaultValue = default(GlobalizationUI.Presentation.ViewModels.CultureNameAndStringValue);
e.Value = value.Equals(defaultValue) ? defaultValue : new GlobalizationUI.Presentation.ViewModels.CultureNameAndStringValue();
}
}
catch (Exception ex)
{
System.Diagnostics.Debugger.Break();
System.Diagnostics.Debug.Print(ex.ToString());
}
}
}
};
foreach (GridViewDataColumn column in settings.Columns)
{
column.Settings.HeaderFilterMode = HeaderFilterMode.CheckedList;
}
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Strings", Action = "CreateNew" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Strings", Action = "Edit" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Strings", Action = "Delete" };
settings.SettingsEditing.Mode = GridViewEditingMode.Inline;
settings.SettingsBehavior.ConfirmDelete = true;
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.CommandColumn.UpdateButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
}).Bind(Model).GetHtml()
StringsController
-------------------------------------------------------------------
using System.Data;
using System.Web.Mvc;
using GlobalizationUI.BusinessObjects;
using Resources.BaseServices.Caching;
using System.Collections.Generic;
using System.ComponentModel;
using GlobalizationUI.Presentation.ViewModels;
using Resources.Util;
namespace GlobalizationUI.Presentation.Controllers
{
public class StringsController : Controller
{
private static string CacheKey_StringTable = "CacheKey_StringTable";
private static string CacheKey_AllCategories = "CacheKey_AllCategories";
private static object padLock = new object();
public ActionResult Index()
{
var stringTable = GetStringTable();
ViewBag.AllCategories = GetCategoryList();
return View(stringTable);
}
public ActionResult StringsPartial()
{
var stringTable = GetStringTable();
ViewBag.AllCategories = GetCategoryList();
return PartialView("_StringsPartial", stringTable);
}
[HttpPost]
public ActionResult CreateNew(StringTableRow row)
{
System.Diagnostics.Debugger.Break();
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(row))
{
System.Diagnostics.Debug.Print(prop.Name);
}
return Content("Hello, there!");
}
[HttpPost]
public ActionResult Edit(DataRow row)
{
return new EmptyResult();
}
[HttpPost]
public ActionResult Delete(long resourceKeyId)
{
return new EmptyResult();
}
private IEnumerable<Category> GetCategoryList()
{
lock (padLock)
{
if (CacheManager.Contains(CacheKey_AllCategories))
{
return CacheManager.Get<IEnumerable<Category>>(CacheKey_AllCategories);
}
}
var list = Category.All;
lock (padLock)
{
CacheManager.Add(CacheKey_AllCategories, list);
}
return list;
}
private List<StringTableRow> GetStringTable()
{
List<StringTableRow> stringTable;
lock (padLock)
{
if (CacheManager.Contains(CacheKey_StringTable))
{
return CacheManager.Get<List<StringTableRow>>(CacheKey_StringTable);
}
}
stringTable = new StringTable().ToListOfStringTableRows();
lock (padLock)
{
CacheManager.Add(CacheKey_StringTable, stringTable);
}
return stringTable;
}
}
}
View Models
-------------------------------------------------------------------
using System.Collections.Generic;
namespace GlobalizationUI.Presentation.ViewModels
{
public class StringTableRow
{
public long ResourceKeyId { get; set; }
public string Key { get; set; }
public long CategoryId { get; set; }
public List<CultureNameAndStringValue> StringValues { get; set; }
}
}
namespace GlobalizationUI.Presentation.ViewModels
{
public class CultureNameAndStringValue
{
public CultureNameAndStringValue() : this(null, null) { }
public CultureNameAndStringValue(string cultureShortName, string stringValue)
{
CultureShortName = cultureShortName;
StringValue = stringValue;
}
public string CultureShortName { get; set; }
public string StringValue { get; set; }
}
}
Model:
-------------------------------------------------------------------
using System.Data;
using GlobalizationUI.Data;
namespace GlobalizationUI.BusinessObjects
{
public class StringTable : DataTable
{
public StringTable()
{
var sql = #"
declare #stmt nvarchar(max)
select #stmt =
isnull(#stmt + ', ', '') +
'max(case when s.CultureId = ' + cast(c.Id as nvarchar(max)) +
' then s.ResourceValue end) as ' + quotename(c.ShortName)
from Culture as c
where c.Supported = 1
select #stmt = '
select
rk.Id AS ResourceKeyId,
rk.Name AS [Key],
c.Id AS CategoryId,
c.Name as CategoryName, ' + #stmt + '
from StringCategory as sc
LEFT OUTER join Category as c on c.Id = sc.CategoryId
RIGHT OUTER JOIN ResourceKey as rk on rk.Id = sc.ResourceKeyId
inner join Strings as s on s.ResourceKeyId = rk.Id
group by rk.Id, rk.Name, c.Id, c.Name
'
exec sp_executesql #stmt = #stmt;";
this.Merge(Database.DefaultDatabase.GetDataTable(sql));
}
}
}
Model to View Model conversion:
-------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlTypes;
namespace GlobalizationUI.Presentation.ViewModels
{
public static class DataTableExtensions
{
public static List<StringTableRow> ToListOfStringTableRows(this DataTable dataTable)
{
var ret = new List<StringTableRow>();
if (dataTable == null || dataTable.Rows.Count == 0) return ret;
foreach (DataRow row in dataTable.Rows)
{
StringTableRow stringTableRow = new StringTableRow();
foreach (DataColumn column in dataTable.Columns)
{
if (string.Compare(column.ColumnName, "ResourceKeyId", true) == 0)
{
stringTableRow.ResourceKeyId = (long)row[column.ColumnName];
}
else if (string.Compare(column.ColumnName, "Key", true) == 0)
{
stringTableRow.Key = (string)row[column.ColumnName];
}
else if (string.Compare(column.ColumnName, "CategoryId", true) == 0)
{
var categoryId = row[column.ColumnName];
stringTableRow.CategoryId = categoryId == DBNull.Value ? 0 : (long)categoryId;
}
else if (string.Compare(column.ColumnName, "CategoryName", true) == 0)
{
continue;
}
else
{
if (stringTableRow.StringValues == null)
stringTableRow.StringValues = new List<CultureNameAndStringValue>();
stringTableRow.StringValues.Add(new CultureNameAndStringValue(column.ColumnName, (string)row[column.ColumnName]));
}
}
ret.Add(stringTableRow);
}
return ret;
}
}
}
The user interface is supposed to look somewhat like the the picture shown above. The number of columns returned by the SQL query is variable depending upon the number of cultures supported by a particular installation/deployment/business client. Hence the need for using unbound columns.
I took this picture not through this code but through an older version of my code when I bound data directly to a System.Data.DataTable and did not use any unbound columns. That was all well until I had to edit the data in the actions at the MVC/server side. So, I switched from using a DataTable to a POCO and used unbound columns for all cultures.
Kindly help.
Okay, though I posted this question only 2 hours or so ago, I've had this trouble for over 8 hours now and have been trying various ways to solve this problem.
And just now, one of the things I did made this problem go away. Here it is.
If you are binding your DevExpress GridViewExtension for ASP.NET MVC to a custom POCO like mine, and that POCO has one or more members that are collections of any kind, then, you must and absolutely must initialize those properties that represent collections in the constructor of your POCO.
For e.g., in my case, the model was a list of StringTableRow's, where StringTableRow was a POCO.
In the StringTableRow class, I had a property named StringValues which was of type IList<CultureNameAndStringValue>, which is a collection. Therefore, for my code to work, I initialized the StringValues property in the construct of my StringTableRow class and everything started to work.
using System.Collections.Generic;
namespace GlobalizationUI.Presentation.ViewModels
{
public class StringTableRow
{
public StringTableRow()
{
// I added this ctor and initialized the
// StringValues property and the broken
// custom binding to unbound columns started
// to work.
StringValues = new List<CultureNameAndStringValue>();
}
public long ResourceKeyId { get; set; }
public string Key { get; set; }
public long CategoryId { get; set; }
public IList<CultureNameAndStringValue> StringValues { get; set; }
}
}

How can i use engine object in my console application

"How can i use engine in my console application"
I shouldn't use the ITemplate-interface and Transform-Method.
I am using Tridion 2011
Could anyone please suggest me.
You can't. The Engine class is part of the TOM.NET and that API is explicitly reserved for use in:
Template Building Blocks
Event Handlers
For all other cases (such as console applications) you should use the Core Service.
There are many good questions (and articles on other web sites) already:
https://stackoverflow.com/search?q=%5Btridion%5D+core+service
http://www.google.com/#q=tridion+core+service
If you get stuck along the way, show us the relevant code+configuration you have and what error message your get (or at what step you are stuck) and we'll try to help from there.
From a console application you should use the Core Service. I wrote a small example using the Core Service to search for items in the content manager.
Console.WriteLine("FullTextQuery:");
var fullTextQuery = Console.ReadLine();
if (String.IsNullOrWhiteSpace(fullTextQuery) || fullTextQuery.Equals(":q", StringComparison.OrdinalIgnoreCase))
{
break;
}
Console.WriteLine("SearchIn IdRef:");
var searchInIdRef = Console.ReadLine();
var queryData = new SearchQueryData
{
FullTextQuery = fullTextQuery,
SearchIn = new LinkToIdentifiableObjectData
{
IdRef = searchInIdRef
}
};
var results = coreServiceClient.GetSearchResults(queryData);
results.ToList().ForEach(result => Console.WriteLine("{0} ({1})", result.Title, result.Id));
Add a reference to Tridion.ContentManager.CoreService.Client to your Visual Studio Project.
Code of the Core Service Client Provider:
public interface ICoreServiceProvider
{
CoreServiceClient GetCoreServiceClient();
}
public class CoreServiceDefaultProvider : ICoreServiceProvider
{
private CoreServiceClient _client;
public CoreServiceClient GetCoreServiceClient()
{
return _client ?? (_client = new CoreServiceClient());
}
}
And the client itself:
public class CoreServiceClient : IDisposable
{
public SessionAwareCoreServiceClient ProxyClient;
private const string DefaultEndpointName = "netTcp_2011";
public CoreServiceClient(string endPointName)
{
if(string.IsNullOrWhiteSpace(endPointName))
{
throw new ArgumentNullException("endPointName", "EndPointName is not specified.");
}
ProxyClient = new SessionAwareCoreServiceClient(endPointName);
}
public CoreServiceClient() : this(DefaultEndpointName) { }
public string GetApiVersionNumber()
{
return ProxyClient.GetApiVersion();
}
public IdentifiableObjectData[] GetSearchResults(SearchQueryData filter)
{
return ProxyClient.GetSearchResults(filter);
}
public IdentifiableObjectData Read(string id)
{
return ProxyClient.Read(id, new ReadOptions());
}
public ApplicationData ReadApplicationData(string subjectId, string applicationId)
{
return ProxyClient.ReadApplicationData(subjectId, applicationId);
}
public void Dispose()
{
if (ProxyClient.State == CommunicationState.Faulted)
{
ProxyClient.Abort();
}
else
{
ProxyClient.Close();
}
}
}
When you want to perform CRUD actions through the core service you can implement the following methods in the client:
public IdentifiableObjectData CreateItem(IdentifiableObjectData data)
{
data = ProxyClient.Create(data, new ReadOptions());
return data;
}
public IdentifiableObjectData UpdateItem(IdentifiableObjectData data)
{
data = ProxyClient.Update(data, new ReadOptions());
return data;
}
public IdentifiableObjectData ReadItem(string id)
{
return ProxyClient.Read(id, new ReadOptions());
}
To construct a data object of e.g. a Component you can implement a Component Builder class that implements a create method that does this for you:
public ComponentData Create(string folderUri, string title, string content)
{
var data = new ComponentData()
{
Id = "tcm:0-0-0",
Title = title,
Content = content,
LocationInfo = new LocationInfo()
};
data.LocationInfo.OrganizationalItem = new LinkToOrganizationalItemData
{
IdRef = folderUri
};
using (CoreServiceClient client = provider.GetCoreServiceClient())
{
data = (ComponentData)client.CreateItem(data);
}
return data;
}
Hope this gets you started.

Building a ViewModel

Greetings,
I have a ViewModel for a ProductCategory.
The ProductCategory has a boolean Active field.
Is is possible to have a single ProductCategoryViewModel and be able to get a collection of all ProductCategories and a collection of ACTIVE ProductCategories?
Or, would I have to create an ActiveProductCategoryViewModel?
I'm using MVVM-Light with RIA in Silverlight...so, I have a ProductCategory service with a GetProductCategories method and a GetActiveProductCategories method. I want to be able to get the ActiveProductCategories to populate a dropdown...but also get ALL the ProductCategories for maintenance and historical purposes etc.
Thanks!
Butcher
I assume you have another ViewModel with a collection of ProductCategoryViewModel objects? If so, I think its fine to have another collection of just the active product categories. I'm not sure you need a separate service method for this, since you can just filter your collection of product categories based on the Active value.
If this view model would be called ProductCategoriesViewModel, it might look like this:
using System.Collections.Generic;
using System.Linq;
using GalaSoft.MvvmLight;
namespace OCEAN.EPP.ViewModel
{
public class ProductCategoriesViewModel : ViewModelBase
{
public ProductCategoriesViewModel()
{
if (IsInDesignMode)
{
ProductCategories = new List<ProductCategoryViewModel>
{
new ProductCategoryViewModel { Active = false },
new ProductCategoryViewModel { Active = false },
new ProductCategoryViewModel { Active = true },
new ProductCategoryViewModel { Active = true },
};
}
else
{
// Code runs "for real": Connect to service, etc...
}
}
public const string ProductCategoriesPropertyName = "ProductCategories";
private List<ProductCategoryViewModel> _productCategories = new List<ProductCategoryViewModel>();
public List<ProductCategoryViewModel> ProductCategories
{
get { return _productCategories; }
set
{
if (_productCategories == value)
return;
_productCategories = value;
FilterActiveProductCategories();
RaisePropertyChanged(ProductCategoriesPropertyName);
}
}
public const string ActiveProductCategoriesPropertyName = "ActiveProductCategories";
private List<ProductCategoryViewModel> _activeProductCategories = new List<ProductCategoryViewModel>();
public List<ProductCategoryViewModel> ActiveProductCategories
{
get { return _activeProductCategories; }
set
{
if (_activeProductCategories == value)
return;
_activeProductCategories = value;
RaisePropertyChanged(ActiveProductCategoriesPropertyName);
}
}
private void FilterActiveProductCategories()
{
ActiveProductCategories = ProductCategories.Where(pc => pc.Active).ToList();
}
}
}

Resources