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());
}
Related
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();
}
}
}
}
A lot of apps have swipable intro screens - You know - those with the dots below which indicate the page one is currently viewing.
What would be the best way to create one in Codename One - a Container with snapToGrid?
I have my own implementation for this use case. There are two classes : TutoDialog which could be in your case the "intro screens" dialog and Caroussel with the dots indicator.
A tuto dialog has a title and some images in parameter. It automatically adjust the number of dots of the caroussel according to the number of images. For my use case, each image is a screenshot of my app with some advise. The tuto dialog contains 3 buttons to navigate between images (next/previous/finish).
public class Caroussel extends Container {
private final static Image CIRCLE = MainClass.getResources().getImage("circle-blue20.png");
private final static Image CIRCLE_EMPTY = MainClass.getResources().getImage("circle-empty-blue20.png");
private Label[] circles;
private int currentIndex = -1;
public Caroussel(int nbItems, boolean selectFirst) {
if (nbItems < 2 || nbItems > 50) {
throw new IllegalArgumentException("Can't create Caroussel component with nbItems<2 || nbItems>50 ! ");
}
this.circles = new Label[nbItems];
setLayout(new BoxLayout(BoxLayout.X_AXIS));
for (int i = 0; i < nbItems; i++) {
circles[i] = new Label("", CIRCLE_EMPTY);
add(circles[i]);
}
if (selectFirst) {
select(0);
}
}
public void select(int index) {
if (index >= 0 && index <= circles.length) {
if (currentIndex > -1) {
circles[currentIndex].setIcon(CIRCLE_EMPTY);
}
circles[index].setIcon(CIRCLE);
currentIndex = index;
repaint();
}
}
public void selectNext() {
if (currentIndex <= circles.length) {
select(currentIndex + 1);
}
}
public void selectPrevious() {
if (currentIndex >= 1) {
select(currentIndex - 1);
}
}}
And
public class TutoDialog extends Dialog {
private Caroussel caroussel = null;
public TutoDialog(String title, Image... images) {
if (images == null) {
return;
}
this.caroussel = new Caroussel(images.length, true);
setTitle(title);
setAutoAdjustDialogSize(true);
getTitleComponent().setUIID("DialogTitle2");
setBlurBackgroundRadius(8.5f);
Tabs tabs = new Tabs();
tabs.setSwipeActivated(false);
tabs.setAnimateTabSelection(false);
int px1 = DisplayUtil.getScaledPixel(800), px2 = DisplayUtil.getScaledPixel(600);
for (Image img : images) {
tabs.addTab("", new Label("", img.scaled(px1, px2)));
}
Container cButtons = new Container(new BorderLayout());
Button bSuivant = new Button("button.suivant");
Button bPrecedent = new Button("button.precedent");
Button bTerminer = new Button("button.terminer");
bPrecedent.setVisible(false);
bTerminer.setVisible(false);
bSuivant.addActionListener(new ActionListener<ActionEvent>() {
public void actionPerformed(ActionEvent evt) {
int currentInd = tabs.getSelectedIndex();
if (currentInd == 0) {
bPrecedent.setVisible(true);
}
if (currentInd + 1 <= tabs.getTabCount() - 1) {
if (caroussel != null)
caroussel.selectNext();
tabs.setSelectedIndex(currentInd + 1);
if (currentInd + 1 == tabs.getTabCount() - 1) {
bTerminer.setVisible(true);
bSuivant.setVisible(false);
cButtons.revalidate();
}
}
};
});
bPrecedent.addActionListener(new ActionListener<ActionEvent>() {
public void actionPerformed(ActionEvent evt) {
int currentInd = tabs.getSelectedIndex();
tabs.setSelectedIndex(currentInd - 1);
bSuivant.setVisible(true);
if (caroussel != null)
caroussel.selectPrevious();
if (currentInd - 1 == 0) {
bPrecedent.setVisible(false);
cButtons.revalidate();
}
};
});
bTerminer.addActionListener(new ActionListener<ActionEvent>() {
#Override
public void actionPerformed(ActionEvent evt) {
tabs.setSelectedIndex(0);
bPrecedent.setVisible(false);
bTerminer.setVisible(false);
bSuivant.setVisible(true);
if (caroussel != null)
caroussel.select(0);
TutoDialog.this.dispose();
}
});
cButtons.add(BorderLayout.WEST, bPrecedent).add(BorderLayout.CENTER, bSuivant).add(BorderLayout.EAST, bTerminer);
add(BoxLayout.encloseY(tabs, BoxLayout.encloseY(FlowLayout.encloseCenter(caroussel), cButtons)));
}
public static void showIfFirstTime(AbstractComponentController ctrl) {
if (ctrl == null) {
Log.p("Can't execute method showIfFirstTime(...) with null AbstractComponentController");
return;
}
String key = getKey(ctrl);
if (ctrl.getTutoDlg() != null && !Preferences.get(key, false)) {
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
Preferences.set(key, true);
ctrl.getTutoDlg().show();
}
});
}
}
public static String getKey(AbstractComponentController ctrl) {
String key = "tuto" + ctrl.getClass().getSimpleName();
if (UserController.getCurrentUser() != null) {
key += "-" + UserController.getCurrentUser().getId();
}
return key;
}
public static boolean isAlreadyShown(AbstractComponentController ctrl) {
return Preferences.get(getKey(ctrl), false);
}
}
It's look like this :
OK - so that is my first attempt and I am pretty content with that:
private void showIntro() {
Display display = Display.getInstance();
int percentage = 60;
int snapWidth = display.getDisplayWidth() * percentage / 100;
int snapHeight = display.getDisplayHeight() * percentage / 100;
Dialog dialog = new Dialog(new LayeredLayout()) {
#Override
protected Dimension calcPreferredSize() {
return new Dimension(snapWidth, snapHeight);
}
};
Tabs tabs = new Tabs();
tabs.setTensileLength(0);
tabs.hideTabs();
int[] colors = {
0xc00000,
0x00c000,
0x0000c0,
0x909000,
0x009090,
};
for (int colorIndex = 0; colorIndex < colors.length; colorIndex++) {
Container containerElement = new Container() {
#Override
protected Dimension calcPreferredSize() {
return new Dimension(snapWidth, snapHeight);
}
};
Style style = containerElement.getAllStyles();
style.setBgTransparency(0xff);
style.setBgColor(colors[colorIndex]);
tabs.addTab("tab" + tabs.getTabCount(), containerElement);
}
int tabCount = tabs.getTabCount();
Button[] buttons = new Button[tabCount];
Style styleButton = UIManager.getInstance().getComponentStyle("Button");
styleButton.setFgColor(0xffffff);
Image imageDot = FontImage.createMaterial(FontImage.MATERIAL_LENS, styleButton);
for (int tabIndex = 0; tabIndex < tabCount; tabIndex++) {
buttons[tabIndex] = new Button(imageDot);
buttons[tabIndex].setUIID("Container");
final int tabIndexFinal = tabIndex;
buttons[tabIndex].addActionListener(aActionEvent -> tabs.setSelectedIndex(tabIndexFinal, true));
}
Container containerButtons = FlowLayout.encloseCenter(buttons);
dialog.add(tabs);
Button buttonWest = new Button("Skip");
buttonWest.setUIID("Container");
buttonWest.getAllStyles().setFgColor(0xffffff);
buttonWest.addActionListener(aActionEvent -> dialog.dispose());
Button buttonEast = new Button(">");
buttonEast.setUIID("Container");
buttonEast.getAllStyles().setFgColor(0xffffff);
buttonEast.addActionListener(aActionEvent -> {
int selectedIndex = tabs.getSelectedIndex();
if (selectedIndex < (tabs.getTabCount() - 1)) {
tabs.setSelectedIndex(selectedIndex + 1, true);
} else {
dialog.dispose();
}
});
Container containerSouth = BorderLayout.south(BorderLayout.centerAbsoluteEastWest(containerButtons, buttonEast, buttonWest));
Style styleContainerSouth = containerSouth.getAllStyles();
styleContainerSouth.setMarginUnit(
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS,
Style.UNIT_TYPE_DIPS);
styleContainerSouth.setMargin(2, 2, 2, 2);
dialog.add(containerSouth);
SelectionListener selectionListener = (aOldSelectionIndex, aNewSelectionIndex) -> {
for (int buttonIndex = 0; buttonIndex < buttons.length; buttonIndex++) {
if (buttonIndex == aNewSelectionIndex) {
buttons[buttonIndex].getAllStyles().setOpacity(0xff);
} else {
buttons[buttonIndex].getAllStyles().setOpacity(0xc0);
}
}
buttonEast.setText((aNewSelectionIndex < (tabs.getTabCount() - 1)) ? ">" : "Finish");
buttonEast.getParent().animateLayout(400);
};
tabs.addSelectionListener(selectionListener);
dialog.addShowListener(evt -> {
buttonEast.getParent().layoutContainer();
selectionListener.selectionChanged(-1, 0);
});
Command command = dialog.showPacked(BorderLayout.CENTER, true);
}
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
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}");
}
}
Just as the name says, I want that for each certain name in an array a value is added to a int.
For example: if there are 3 strings of the same name in the array, then 3 times 50 will be added to the value.
This is my script I have now:
var lootList = new Array();
var interaction : Texture;
var interact = false;
var position : Rect;
var ching : AudioClip;
var lootPrice = 0;
function Update()
{
print(lootList);
if ("chalice" in lootList){
lootPrice += 50;
}
}
function Start()
{
position = Rect( ( Screen.width - interaction.width ) /2, ( Screen.height - interaction.height ) /2, interaction.width, interaction.height );
}
function OnTriggerStay(col : Collider)
{
if(col.gameObject.tag == "loot")
{
interact = true;
if(Input.GetKeyDown("e"))
{
if(col.gameObject.name == "chalice")
{
Destroy(col.gameObject);
print("chaliceObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("chalice");
}
if(col.gameObject.name == "moneyPouch")
{
Destroy(col.gameObject);
print("moneyPouchObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("moneyPouch");
}
if(col.gameObject.name == "ring")
{
Destroy(col.gameObject);
print("ringObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("ring");
}
if(col.gameObject.name == "goldCoins")
{
Destroy(col.gameObject);
print("coldCoinsObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("goldCoins");
}
if(col.gameObject.name == "plate")
{
Destroy(col.gameObject);
print("plateObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("plate");
}
}
}
}
function OnTriggerExit(col : Collider)
{
if(col.gameObject.tag == "pouch")
{
interact = false;
}
}
function OnGUI()
{
if(interact == true)
{
GUI.DrawTexture(position, interaction);
GUI.color.a = 1;
}
}
It's for a game I'm making where you can steal items for extra score points.
I've tried using the for(i = 0; i < variable.Length; i++) but that didn't seem to work.
The only thing I can think of now is using booleans to add it once. But that isn't memory friendly.
Help is appreciated and thanks in advance!
You could use the standard .forEach(callback) method:
lootList.forEach(function(value, index, array)
{
if (value === "chalice") { lootPrice += 50; }
});
If you don't have that method, you could implement it like this:
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback) {
for(var i = 0; i < this.length; i++) { callback(this[i], i, this); }
}
}