update client database for IdentityServer4 - identityserver4

I have identityServer4 as my oAuth server in my net core appilication. I was able to initialize my client database using the following code:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
SeedData.EnsureSeedData(serviceScope);
}
}
}
The migration and client initialization is done using
public class SeedData
{
public static void EnsureSeedData(IServiceScope serviceScope)
{
Console.WriteLine("Seeding database...");
serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
context.Database.Migrate();
EnsureSeedData(context);
Console.WriteLine("Done seeding database.");
Console.WriteLine();
}
private static void EnsureSeedData(ConfigurationDbContext context)
{
if (!context.Clients.Any())
{
Console.WriteLine("Clients being populated");
foreach (var client in Config.GetClients().ToList())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("Clients already populated, update clients");
foreach (var client in Config.GetClients().ToList())
{
var item = context.Clients.Where(c => c.ClientId == client.ClientId).FirstOrDefault();
if(item == null)
{
context.Clients.Add(client.ToEntity());
} else {
var model = client.ToEntity();
model.Id = item.Id;
context.Entry(item).CurrentValues.SetValues(model);
}
}
context.SaveChanges();
}
if (!context.IdentityResources.Any())
{
Console.WriteLine("IdentityResources being populated");
foreach (var resource in Config.GetIdentityResources().ToList())
{
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("IdentityResources already populated");
foreach (var resource in Config.GetIdentityResources().ToList())
{
var item = context.IdentityResources.Where(c => c.Name == resource.Name).FirstOrDefault();
if (item == null)
{
context.IdentityResources.Add(resource.ToEntity());
}
else
{
var model = resource.ToEntity();
model.Id = item.Id;
context.Entry(item).CurrentValues.SetValues(model);
}
}
context.SaveChanges();
}
if (!context.ApiResources.Any())
{
Console.WriteLine("ApiResources being populated");
foreach (var resource in Config.GetApiResources().ToList())
{
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("ApiResources already populated");
foreach (var resource in Config.GetApiResources().ToList())
{
var item = context.ApiResources.Where(c => c.Name == resource.Name).FirstOrDefault();
if (item == null)
{
context.ApiResources.Add(resource.ToEntity());
}
else
{
var model = resource.ToEntity();
model.Id = item.Id;
context.Entry(item).CurrentValues.SetValues(model);
}
}
context.SaveChanges();
}
}
}
The initialization of the client database works well. However, there are problems to update the client database. Some of the records are not updated. Is there a better way to do this?

After some struggle, I found a solution that works for me. Basically, I created a table, ClientVersion, that track clients definition changes.
Here is my new version of SeedData.cs.
public class SeedData
{
public static void EnsureSeedData(IServiceScope serviceScope)
{
Console.WriteLine("Seeding database...");
serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
context.Database.Migrate();
var versionContext = serviceScope.ServiceProvider.GetRequiredService<VersionContext>();
versionContext.Database.Migrate();
EnsureSeedData(context, versionContext);
Console.WriteLine("Done seeding database.");
Console.WriteLine();
}
private static void EnsureSeedData(ConfigurationDbContext context, VersionContext versionContext)
{
ClientVersion version = versionContext.ClientVersion.FirstOrDefault();
bool blUpdate = version == null ? true : (Config.CurrentVersion > version.Version ? true: false);
if(blUpdate)
{
if(version == null)
{
version = new ClientVersion()
{
Version = Config.CurrentVersion,
};
versionContext.ClientVersion.Add(version);
} else
{
version.Version = Config.CurrentVersion;
versionContext.ClientVersion.Update(version);
}
versionContext.SaveChanges();
}
if (!context.Clients.Any())
{
Console.WriteLine("Clients being populated");
foreach (var client in Config.GetClients().ToList())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("Clients already populated, update clients");
if (blUpdate)
{
foreach (var client in Config.GetClients().ToList())
{
var item = context.Clients
.Include(x => x.RedirectUris)
.Include(x => x.PostLogoutRedirectUris)
.Include(x => x.ClientSecrets)
.Include(x => x.Claims)
.Include(x => x.AllowedScopes)
.Include(x => x.AllowedCorsOrigins)
.Include(x => x.AllowedGrantTypes)
.Where(c => c.ClientId == client.ClientId).FirstOrDefault();
if (item != null)
{
context.Clients.Remove(item);
}
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
}
if (!context.IdentityResources.Any())
{
Console.WriteLine("IdentityResources being populated");
foreach (var resource in Config.GetIdentityResources().ToList())
{
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("IdentityResources already populated");
if (blUpdate)
{
foreach (var resource in Config.GetIdentityResources().ToList())
{
var item = context.IdentityResources.Where(c => c.Name == resource.Name).FirstOrDefault();
if (item != null)
{
context.IdentityResources.Remove(item);
}
context.IdentityResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
}
if (!context.ApiResources.Any())
{
Console.WriteLine("ApiResources being populated");
foreach (var resource in Config.GetApiResources().ToList())
{
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
else
{
Console.WriteLine("ApiResources already populated");
if (blUpdate)
{
foreach (var resource in Config.GetApiResources().ToList())
{
var item = context.ApiResources.Where(c => c.Name == resource.Name).FirstOrDefault();
if (item != null)
{
context.ApiResources.Remove(item);
}
context.ApiResources.Add(resource.ToEntity());
}
context.SaveChanges();
}
}
}
}

Related

downloadUrlToStorageInBackground in ImageList model for imageViewer downloads & overrides the image every time

class ImageList implements ListModel<Image> {
private int selection;
private Image[] images;
private EventDispatcher listeners = new EventDispatcher();
public ImageList() {
this.images = new EncodedImage[imageURLs.length];
}
public Image getItemAt(final int index) {
if (images[index] == null) {
images[index] = placeholderForTable;
Util.downloadUrlToStorageInBackground(imageURLs[index], "list" + index, (e) -> {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("list" + index));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch (IOException err) {
err.printStackTrace();
}
});
}
return images[index];
}
public int getSize() {
return imageURLs.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeListener(l);
}
public void addSelectionListener(SelectionListener l) {
}
public void removeSelectionListener(SelectionListener l) {
}
public void addItem(Image item) {
}
public void removeItem(int index) {
}
}
protected void postMenuForm(Form f) {
BusinessForumImagesConnection bfic = new BusinessForumImagesConnection();
bfic.businessForumImagesConnectionMethod(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (bfic.response != null) {
for (int i = 0; i < imgLoop; i++) {
HashMap hm = (HashMap) bfic.response.get(i);
String imgUrl = (String) hm.get("imgUrl");
imageURLs[i] = imgUrl;
}
}
}
});
if (imageURLs != null) {
ImageList imodel = new ImageList();
ImageViewer iv = new ImageViewer(imodel.getItemAt(0));
iv.setImageList(imodel);
Container adsContainer = BoxLayout.encloseY(adsLabel, iv);
slideIndex = 0;
Runnable r = new Runnable() {
public void run() {
if (slideIndex < imodel.getSize()) {
nextImage = (Image) imodel.getItemAt(slideIndex);
if (nextImage != null) {
iv.setImage(nextImage);
}
slideIndex++;
} else {
slideIndex = 0;
}
}
};
if (uITimer == null) {
uITimer = new UITimer(r);
}
if (uITimer != null) {
uITimer.schedule(5000, true, f); //5 seconds
}
f.add(BorderLayout.SOUTH, adsContainer);
adsContainer.setLeadComponent(adsLabel);
adsLabel.addActionListener((e) -> {
showForm("BusinessForum", null);
});
}
}
I had used URLImage.createToStorage before but imageViewer didnt work properly so I have used ImageList model. But everytime the form is opened, it jst redownloads the imgs and overrides them in storage, that makes the app slower. How can I make sure if the image is already downloaded, it doesnt download it again and jst shows them in imgViewer? thankyou
The download method will always download regardless...
You need to check if the Storage file exists and if so load that.
See the WebServices/Dogs demo in the new kitchen sink: http://www.codenameone.com/blog/kitchensink-ii.html

WPF Calender Week

I'm new in here and at programming. I'm making a program that only shows one week at a time. I have some appointments spanning over several weeks, and my question is: Is there a way to only show the "appointments" of the week you are currently in?
So far i have this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var googleCal = new GoogleClass();
foreach (var googleEvent in googleCal.GoogleEvents)
{
if ((googleEvent.StartDate.Value.DayOfWeek - googleEvent.StartDate.Value.DayOfWeek)
{
listBox.Items.Add(googleEvent.Title + " " + googleEvent.StartDate);
}
}
}
}
public class GoogleEvents
{
public string Title { get; set; }
public DateTime? StartDate { get; set; }
}
class GoogleClass
{
public List<GoogleEvents> GoogleEvents = new List<GoogleEvents>();
static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
static string ApplicationName = "Google Calendar API .NET Quickstart";
public GoogleClass()
{
UserCredential credential;
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
EventsResource.ListRequest request = service.Events.List("primary");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
// List events.
Events events = request.Execute();
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
GoogleEvents.Add(new GoogleEvents {Title = eventItem.Summary, StartDate = eventItem.Start.DateTime});
}
}
}
}
I have figured it out
var googleCal = new GoogleClass();
var ugedag = DateTime.Now.DayOfWeek;
var getMondays = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(6));
var getTuesdays = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(5));
var getWednesday = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(4));
var getThursday = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(3));
var getFriday = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(2));
var getSaturday = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(1));
var getSunday = googleCal.GoogleEvents.Where(e => e.StartDate < DateTime.Now.AddDays(0));
foreach (var googleCalGoogleEvent in googleCal.GoogleEvents)
{
listBox.Items.Add(googleCalGoogleEvent.Title);
}
if (ugedag == DayOfWeek.Monday)
{
foreach (var events in getMondays)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Tuesday)
{
foreach (var events in getTuesdays)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Wednesday)
{
foreach (var events in getWednesday)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Thursday)
{
foreach (var events in getThursday)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Friday)
{
foreach (var events in getFriday)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Saturday)
{
foreach (var events in getSaturday)
{
NewMethod(events);
}
}
if (ugedag == DayOfWeek.Sunday)
{
foreach (var events in getSunday)
{
NewMethod(events);
}
}
}
private void NewMethod(GoogleEvents events)
{
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Monday)
{
Monday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Tuesday)
{
Tuesday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Wednesday)
{
Wednsday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Thursday)
{
Thuesday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Friday)
{
Friday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Saturday)
{
Saturday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
if (events.StartDate.Value.DayOfWeek == DayOfWeek.Sunday)
{
Sunday.Items.Add($"{events.Title} \n{events.StartDate:dd-MM HH:MM}-{events.EndDate:HH:MM}");
}
}

CakePHP 3 : delete and update array from cookie

I'm using CakePHP 3.2 for writing a shopping cart application.
I'm using cookie to add items to the cart.
Now I want to update and delete value from cart. so that if user clicks on the same product add to cart with a different quantity value the existing record will be deleted and new will be added to cart.
This is my addToCart() method.
public function addToCart()
{
$this->loadModel('Products');
if ($this->request->is('post')) {
$p_id = $this->request->data('product_id');
$p_quantity = $this->request->data('qnty');
$product = $this->Products->get($p_id);
$product->quantity = $p_quantity;
if (!$product) {
throw new NotFoundException(__('Invalid Product'));
}
$cart = $this->Cookie->read('Cart') ? $this->Cookie->read('Cart') : [];
$itemInCart = false;
$itemUpdated = false;
if ($cart != null) {
foreach($cart as $cart_item):
if ($cart_item['id'] == $p_id) {
if ($cart_item['quantity'] != $p_quantity) {
$this->Cookie->delete('Cart.'.$cart_item); // line 148
$cart[] = $product;
$this->Cookie->write('Cart', $cart);
$itemsCount = count($this->Cookie->read('Cart'));
$this->Flash->success('Product updated in cart');
return $this->redirect($this->referer);
}
$itemInCart = true;
}
endforeach;
}
if (!$itemInCart) {
$cart[] = $product;
$this->Cookie->write('Cart', $cart);
$itemsCount = count($this->Cookie->read('Cart'));
if ($itemUpdated) {
$this->Flash->success(__('Product updated in cart'));
} else {
$this->Flash->success(__('Product added to cart'));
}
return $this->redirect($this->referer());
} else {
$this->Flash->success(__('Product is already in cart'));
return $this->redirect($this->referer());
}
}
}
But this is giving error as
Notice (8): Array to string conversion [APP/Controller/OrdersController.php, line 148]
How could I update the quantity value in the cart.
Try the following:
public function addToCart()
{
$this->loadModel('Products');
if ($this->request->is('post')) {
$p_id = $this->request->data('product_id');
$p_quantity = $this->request->data('qnty');
$product = $this->Products->get($p_id);
if (!$product) {
throw new NotFoundException(__('Invalid Product'));
}
$product->quantity = $p_quantity;
$cart = $this->Cookie->read('Cart') ? $this->Cookie->read('Cart') : [];
$itemInCart = false;
$new_cart = [];
if ($cart != null) {
foreach($cart as $cart_item):
if ($cart_item['id'] == $p_id) {
if($p_quantity == 0){
//Removed the item from cart and set itemInCart to true
$itemInCart = true;
}else{
//update the quantity of item
$new_cart[] = $product;
$itemInCart = true;
}
}else{
$new_cart[] = $cart_item;
}
endforeach;
}
if ($itemInCart) {
$this->Cookie->write('Cart', $new_cart);
$this->Flash->success(__('Product updated in cart'));
} else {
$cart[] = $product;
$this->Cookie->write('Cart', $cart);
$this->Flash->success(__('Product added to cart'));
}
return $this->redirect($this->referer);
}
}

how can i inject IContentManager in Timer callback (Orchard CMS)

public Models.ManagedUsersPart GetManagedUsers(int ManagedUsersId)
{
return _cacheManager.Get(ManagedUsersId, ctx =>
{
MonitorManagedUserSignal(ctx, ManagedUsersId);
Timer = new Timer(t => DoUpdate(_contentManager,ManagedUsersId), "c", TimeSpan.FromMinutes(2), TimeSpan.FromMilliseconds(-1));
var managedusers = _contentManager.Get<ManagedUsersPart>(ManagedUsersId);
return managedusers;
});
}
and this is my DoUpdate function:
public void DoUpdate(IContentManager contentmanager,int ManagedUsersId)
{
var transation = _iworkcontext.CreateWorkContextScope().Resolve<ITransactionManager>();
transation.RequireNew();
var manager = getmanager();
var modifiemanageruser = manager.Get<ManagedUsersPart>(ManagedUsersId);
var modi = GetManagedUsers(ManagedUsersId);
modifiemanageruser.InvitedCount = modi.InvitedCount;
}
and ,this is my getmanager function:
public IContentManager getmanager()
{
if (Timermanager == null)
{
Timermanager = _iworkcontext.CreateWorkContextScope().Resolve<IContentManager>();
}
return Timermanager;
}
The question is "modifiemanageruser.InvitedCount = modi.InvitedCount"
this code does not persist update to database,anyone can help?

Finding all Images in a FlowDocument

Since I am pretty new to WPF FlowDocuments I would like to ask if the code below is correct. It is supposed to return all Images contained in a FlowDocument as List:
List<Image> FindAllImagesInParagraph(Paragraph paragraph)
{
List<Image> result = null;
foreach (var inline in paragraph.Inlines)
{
var inlineUIContainer = inline as InlineUIContainer;
if (inlineUIContainer != null)
{
var image = inlineUIContainer.Child as Image;
if (image != null)
{
if (result == null)
result = new List<Image>();
result.Add(image);
}
}
}
return result;
}
private List<Image> FindAllImagesInDocument(FlowDocument Document)
{
List<Image> result = new List<Image>();
foreach (var block in Document.Blocks)
{
if (block is Table)
{
var table = block as Table;
foreach (TableRowGroup rowGroup in table.RowGroups)
{
foreach (TableRow row in rowGroup.Rows)
{
foreach (TableCell cell in row.Cells)
{
foreach (var block2 in cell.Blocks)
{
if (block2 is Paragraph)
{
var paragraph = block2 as Paragraph;
var images = FindAllImagesInParagraph(paragraph);
if (images != null)
result.AddRange(images);
}
else if (block2 is BlockUIContainer)
{
var container = block as BlockUIContainer;
if (container.Child is Image)
{
var image = container.Child as Image;
result.Add(image);
}
}
}
}
}
}
}
else if (block is Paragraph)
{
var paragraph = block as Paragraph;
var images = FindAllImagesInParagraph(paragraph);
if (images != null)
result.AddRange(images);
}
else if (block is BlockUIContainer)
{
var container = block as BlockUIContainer;
if(container.Child is Image)
{
var image = container.Child as Image;
result.Add(image);
}
}
}
return result.Count > 0 ? result : null;
}
LINQ is just freaking magical:
public IEnumerable<Image> FindImages(FlowDocument document)
{
return document.Blocks.SelectMany(FindImages);
}
public IEnumerable<Image> FindImages(Block block)
{
if (block is Table)
{
return ((Table)block).RowGroups
.SelectMany(x => x.Rows)
.SelectMany(x => x.Cells)
.SelectMany(x => x.Blocks)
.SelectMany(FindImages);
}
if (block is Paragraph)
{
return ((Paragraph) block).Inlines
.OfType<InlineUIContainer>()
.Where(x => x.Child is Image)
.Select(x => x.Child as Image);
}
if (block is BlockUIContainer)
{
Image i = ((BlockUIContainer) block).Child as Image;
return i == null
? new List<Image>()
: new List<Image>(new[] {i});
}
throw new InvalidOperationException("Unknown block type: " + block.GetType());
}
Little change in Code to add coverage for List
public static IEnumerable<Image> FindImages(FlowDocument document)
{
return document.Blocks.SelectMany(block => FindImages(block));
}
public static IEnumerable<Image> FindImages(Block block)
{
if (block is Table)
{
return ((Table)block).RowGroups
.SelectMany(x => x.Rows)
.SelectMany(x => x.Cells)
.SelectMany(x => x.Blocks)
.SelectMany(innerBlock => FindImages(innerBlock));
}
if (block is Paragraph)
{
return ((Paragraph)block).Inlines
.OfType<InlineUIContainer>()
.Where(x => x.Child is Image)
.Select(x => x.Child as Image);
}
if (block is BlockUIContainer)
{
Image i = ((BlockUIContainer)block).Child as Image;
return i == null
? new List<Image>()
: new List<Image>(new[] { i });
}
if (block is List)
{
return ((List)block).ListItems.SelectMany(listItem => listItem
.Blocks
.SelectMany(innerBlock => FindImages(innerBlock)));
}
throw new InvalidOperationException("Unknown block type: " + block.GetType());
}
static IEnumerable<T> GetElementsOfType<T>(DependencyObject parent) where T : class
{
var childElements = LogicalTreeHelper.GetChildren(parent).OfType().ToList();
return childElements.SelectMany(GetElementsOfType<T>).Union(childElements.OfType<T>());
}
....
var images = GetElementsOfType<Image>(document)
Little change in Code to add coverage for Figure and Floater
public static IEnumerable<Image> FindImages(FlowDocument document)
{
return document.Blocks.SelectMany(block => FindImages(block));
}
public static IEnumerable<Image> FindImages(Block block)
{
if (block is Paragraph)
{
List<Image> toReturn = new List<Image>();
var check = ((Paragraph)block).Inlines;
foreach (var i in check)
{
if (i is InlineUIContainer)
{
var inlineUiContainer = i as InlineUIContainer;
Image image = ((InlineUIContainer)inlineUiContainer).Child as Image;
if(image != null)
{
toReturn.Add(image);
}
}
else if (i is Figure)
{
var figure = i as Figure;
var images = figure.Blocks.SelectMany(blocks => FindImages(blocks));
toReturn.AddRange(images);
}
else if (i is Floater)
{
var floater = i as Floater;
var images = floater.Blocks.SelectMany(blocks => FindImages(blocks));
toReturn.AddRange(images);
}
}
return toReturn;
}
if (block is Table)
{
return ((Table)block).RowGroups
.SelectMany(x => x.Rows)
.SelectMany(x => x.Cells)
.SelectMany(x => x.Blocks)
.SelectMany(innerBlock => FindImages(innerBlock));
}
if (block is BlockUIContainer)
{
Image i = ((BlockUIContainer)block).Child as Image;
return i == null
? new List<Image>()
: new List<Image>(new[] { i });
}
if (block is List)
{
return ((List)block).ListItems.SelectMany(listItem => listItem
.Blocks
.SelectMany(innerBlock => FindImages(innerBlock)));
}
throw new InvalidOperationException("Unknown block type: " + block.GetType());
}

Resources