I'm updating a pivot viewer application and have run into the following issue. Hopefully someone will have an answer as I'm stuck.
The issue: When the page is loaded the side with properties and other features load fine, but the trading cards don't load any images. Some of them load the default white background while the majority show a dark grey, almost black background. All of them can be zoomed into and show all the properties, but no images.
Debugging: I've discovered that commenting out some of the properties causes the images to load correctly every time. If I comment out only 1 or 2 then the images will load some of the time (about 2 out of 10 page refreshes). Currently there are 29 properties contained in a list and the data is being loaded from a database and then used in the pivotviewer.ItemsSource.
Any ideas?
Code with some name changes (the option two one is the one with the properties I'm commenting out):
MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
PivotViewModel pivotModel = new PivotViewModel();
CollectionsComboBox.SelectedIndex = 0;
this.DataContext = pivotModel;
}
private void DropDown_ItemSelected(object sender, EventArgs e)
{
// Process selected index change here
if (((ComboBox)sender).SelectedValue == "Option One")
{
OptionOnePivotViewModel OptionOnePivot = new OptionOnePivotViewModel();
PivotViewer.ItemsSource = OptionOnePivot.Data;
PivotViewer.PivotProperties = OptionOnePivot.PivotProperties;
PivotViewer.ItemTemplates = OptionOnePivot.TemplateCollection;
PivotViewer.ItemAdornerStyle = blankAdorner;
}
else
{
OptionTwoPivotViewModel OptionTwoPivot = new OptionTwoPivotViewModel();
PivotViewer.ItemsSource = OptionTwoPivot.Data;
PivotViewer.PivotProperties = OptionTwoPivot.PivotProperties;
PivotViewer.ItemAdornerStyle = basicAdorner;
PivotViewer.ItemTemplates = OptionTwoPivot.TemplateCollection;
}
}
OptionTwoPivotViewModel.cs:
public OptionTwoPivotViewModel()
{
DomainContext = new OptionTwoDomainContext();
Data = DomainContext.Load(DomainContext.GetHRDatasQuery()).Entities;
PivotProperties = getPivotProperties();
SmallTemplate = "EmpSmall";
TemplateCollection = new PivotViewerItemTemplateCollection()
{
(PivotViewerItemTemplate) Application.Current.Resources[SmallTemplate]
};
}
private List<PivotViewerProperty> getPivotProperties()
{
List<PivotViewerProperty> properties = new List<PivotViewerProperty>
{
new PivotViewerStringProperty{ Id="Name", Options=PivotViewerPropertyOptions.CanSearchText, DisplayName="Name", Binding=new System.Windows.Data.Binding("Name")},
new PivotViewerStringProperty{ Id="Status", Options=PivotViewerPropertyOptions.CanFilter, DisplayName="Status", Binding=new System.Windows.Data.Binding("Status")},
new PivotViewerDateTimeProperty{ Id="StartDate", Options=PivotViewerPropertyOptions.CanFilter, DisplayName="Start Date", Binding=new System.Windows.Data.Binding("StartDate")},
//additional properties follow...
};
return properties;
Edit: I've noticed that if I set a breakpoint in the following property getter then continue the images also load fine.
public ImageSource BackgroundImage
{
get
{
string location = Image_Location;
location = location.Substring(location.LastIndexOf("/"));
Uri uri;
if (Image_Location.Contains(".gif"))
{
uri = new Uri(Image_Location, UriKind.Absolute);
}
else
{
var host = Application.Current.Host.Source.Host;
uri = new Uri("https://" + host + "/fileLibrary/employees/images/500"+location, UriKind.RelativeOrAbsolute);
}
// set the image source
BitmapImage bmpImg = new BitmapImage(uri);
_loaded = _backgroundImage != null;
if (!_loaded)
{
bmpImg.ImageOpened += ImageOpened;
bmpImg.ImageFailed += ImageFailed;
}
return new BitmapImage(uri);
}
TemplateCollection = new PivotViewerItemTemplateCollection()
{
(PivotViewerItemTemplate) Application.Current.Resources[SmallTemplate]
};
Not assigning a property in the initializer above?
Related
I'm trying to create a pdf using MigraDoc. Here's a list of the libraries that I'm using:
MigraDoc.DocumentObjectModel
MigraDoc.DocumentObjectModel.Tables
MigraDoc.Rendering
It throws me an error on printer.RenderDocument(). Code below
private async Task SavePDF()
{
filePath = emulatorFolderPath + "/Signed/" + _reportInformationViewModel.SelectedClient.Username + "-" + DateTime.Now.ToString("dd_MM_yyyy HH-mm") + ".pdf";
MigraDocRendering.PdfDocumentRenderer printer = new MigraDocRendering.PdfDocumentRenderer
{
Document = document
};
printer.RenderDocument();
printer.PdfDocument.Save(filePath);
}
PS: I don't need to use a private font.
I've resolved by implementing IFontResolver
I've added a folder Fonts that contains Open-Sans font.
I've created a folder Helpers that contains a class called GenericFontResolver:
public class GenericFontResolver : IFontResolver
{
public string DefaultFontName => "OpenSans";
public byte[] GetFont(string faceName)
{
if (faceName.Contains(DefaultFontName))
{
var assembly = typeof(ReportPreviewAndSignatureViewModel).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream($"PDFDemo.Fonts.{faceName}.ttf");
using (var reader = new StreamReader(stream))
{
var bytes = default(byte[]);
using (var ms = new MemoryStream())
{
reader.BaseStream.CopyTo(ms);
bytes = ms.ToArray();
}
return bytes;
}
}
else
return GetFont(DefaultFontName);
}
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
{
var fontName = string.Empty;
switch (familyName)
{
case "Open Sans":
case "OpenSans":
fontName = "OpenSans";
if (isBold && isItalic)
fontName = $"{fontName}-BoldItalic";
else if (isBold)
fontName = $"{fontName}-Bold";
else if (isItalic)
fontName = $"{fontName}-Italic";
else
fontName = $"{fontName}-Regular";
return new FontResolverInfo(fontName);
default:
break;
}
return null;
}
}
Then, on the constructor of the class that needs the font I've added:
GlobalFontSettings.FontResolver = new GenericFontResolver();
Then, when I'm creating the table you must add:
Style style = document.Styles["Normal"];
style.Font.Name = "OpenSans";
I have two action methods in my Controller class:
DetailsAll: to get some data and display in the view
SaveAsPDF: Called on windows.load of DetailsAll.cshtml which should save DetailsAll view as pdf
My issue is in SaveAsPDF Action method. Here I am trying to use Rotativa ActionAsPdf and subsequently BuildFile methods to generate and save the PDF. However, when executing the line "BuildFile", it is not hitting the breakpoint in my DetailsAll Action method, subsequently causing the PDF to be generated blank.
Could you please help where I am going wrong?
[HttpGet]
public ActionResult DetailsAll()
{
var selectionBuilder = builderFactory.GetGeocodeReportSelectionViewModelBuilder();
var companyList = selectionBuilder.Build();
List<GeocodeReportViewModel> viewModel = new List<GeocodeReportViewModel>();
foreach(SelectListItem record in companyList.Companies)
{
var builder = builderFactory.GetGeocodeReportViewModelBuilder(int.Parse(record.Value));
viewModel.Add(builder.Build());
}
var model = new AllGeocodeReportViewModel
{
GeocodeReports = viewModel
};
return View(model);
}
[HttpGet]
public string SaveAsPDF()
{
var report = new ActionAsPdf("DetailsAll")
{
FileName = "OEM_GeocodeReport_" + System.DateTime.Now.ToString("MMYY") + ".pdf",
PageSize = Size.A4,
PageOrientation = Orientation.Landscape,
PageMargins = { Left = 1, Right = 1 }
};
byte[] pdf = report.BuildFile(ControllerContext);
System.IO.File.WriteAllBytes("C:\\" + report.FileName, pdf);
return "true";
}
Finally found the issue after extensive search. I need to send Authentication cookies along with the BuildFile request for this to work. Added the below code and it generates PDF correctly now:
public void SaveAsPDF()
{
var cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k].Value);
var report = new ActionAsPdf("DetailsAll")
{
FileName = "OEM_GeocodeReport_" + System.DateTime.Now.ToString("MMyy") + ".pdf",
PageSize = Size.A4,
PageOrientation = Orientation.Portrait,
PageMargins = { Left = 3, Right = 3 },
FormsAuthenticationCookieName = System.Web.Security.FormsAuthentication.FormsCookieName,
Cookies = cookies
};
byte[] pdf = report.BuildFile(ControllerContext);
System.IO.File.WriteAllBytes("C:\\" + report.FileName, pdf);
}
Currently on my app when the user selects their 'symptom' they are directed to the detail page which shows their symptom chart with the populated feedback data from their selected symptom.
Is their a way i can add a swipe gesture to allow the user to swipe to the next symptom chart without having to go back to main symptoms page and selecting a symptom.
Currently this is how i populate my chart :
public async Task GetSymptomFeedback(string id)
{
SymptomFeedbackData.Clear();
symptomChart.Series.Clear();
BusyIndicator.IsRunning = true;
SymptomFeedbackData = await symptomsfeedbackmanager.getUserSymptomFeedback(id);
foreach (var FeedbackItem in SymptomFeedbackData)
{
FeedbackItem.Idusersymptomid = FeedbackItem.Id + ',' + FeedbackItem.Usersymptomid;
}
IEnumerable<SymptomFeedback> OrdreredFeedbackData = SymptomFeedbackData.OrderBy(X => X.DateTime);
LineSeries columnseries = new LineSeries
{
ItemsSource = OrdreredFeedbackData,
XBindingPath = "DateTime",
YBindingPath = "Intensity",
DataMarker = new ChartDataMarker
{
ShowLabel = true,
ShowMarker = true,
MarkerHeight = 5,
MarkerWidth = 5,
MarkerColor = Xamarin.Forms.Color.Purple
}
};
BusyIndicator.IsRunning = false;
symptomChart.PrimaryAxis.ShowTrackballInfo = true;
if (columnseries.ItemsSource != null)
{
symptomChart.Series.Add(columnseries);
}
symptomChart.ChartBehaviors.Add(new ChartTrackballBehavior());
//Sort Collection by datetime
SymptomsList.ItemsSource = OrdreredFeedbackData.Reverse();
}
Solution:
Through your code, we can see you query the data through the id of symptom. So, I guess you pass this id as parameter when you go to the detail page from main symptoms page.
Is their a way i can add a swipe gesture to allow the user to swipe to
the next symptom chart without having to go back to main symptoms page
and selecting a symptom.
In additional, you can pass a array of id of all symptoms to detail page. Let's name this array as symptomIdArray.
Then add a SwipeGestureRecognizer to your view.
var DownSwipeGesture = new SwipeGestureRecognizer { Direction = SwipeDirection.Down };
var UpSwipeGesture = new SwipeGestureRecognizer { Direction = SwipeDirection.Up };
DownSwipeGesture.Swiped += OnSwiped;
UpSwipeGesture.Swiped += OnSwiped;
this.Content.GestureRecognizers.Add(DownSwipeGesture);
this.Content.GestureRecognizers.Add(UpSwipeGesture);
In the OnSwiped, you can get last or next id through the symptomIdArray and currentID , and then you can choose to reload your current page or go to a new page to swipe to the next symptom chart, here is code:
public Array symptomIdArray; // ids of all symptom
public string currentID; // You selected id of current symptom
void OnSwiped(object sender, SwipedEventArgs e)
{
int index = Array.IndexOf(symptomIdArray, currentID);
switch (e.Direction)
{
case SwipeDirection.Up:
if (index ==0)
{
//first one
break;
}
string lastID = (string)symptomIdArray.GetValue(index-1);
//1.You can refresh current page with lastId
GetSymptomFeedback(lastID);
//2.You can go to a new page with lastID ID and symptomIdArray
Navigation.PushAsync(new NewPage(lastID, symptomIdArray));
break;
case SwipeDirection.Down:
// Handle the swipe
if (index == symptomIdArray.Length-1)
{
//Last one, no more
break;
}
string nextID = (string)symptomIdArray.GetValue(index+1);
//1.You can refresh current page with next currentID
GetSymptomFeedback(nextID);
//2.You can go to a new page with nextID ID and symptomIdArray
Navigation.PushAsync(new NewPage(nextID, symptomIdArray));
break;
}
}
Update:
Add SwipeGestureRecognizer:
SfChart chart = new SfChart();
chart.Title.Text = "Chart";
//Config chart....
...
chart.Series.Add(series);
this.Content = chart;
var DownSwipeGesture = new SwipeGestureRecognizer { Direction = SwipeDirection.Down };
var UpSwipeGesture = new SwipeGestureRecognizer { Direction = SwipeDirection.Up };
DownSwipeGesture.Swiped += OnSwiped;
UpSwipeGesture.Swiped += OnSwiped;
chart.GestureRecognizers.Add(DownSwipeGesture);
chart.GestureRecognizers.Add(UpSwipeGesture);
And onSwipe:
void OnSwiped(object sender, SwipedEventArgs e)
{
switch (e.Direction)
{
case SwipeDirection.Up:
Console.WriteLine("up");
break;
case SwipeDirection.Down:
Console.WriteLine("down");
break;
}
}
Let me know if you have any question.
I am following this article for Select Multiple Images From Gallery in Xamarin Forms.
I completed the feature in android part but the picture path contains only the picture name, extensions are missing when saving path.
To upload the image to the server I need the complete image name with extension. So how can I save the complete path of the selected images with the extension?
Following method capture the image path:
public String GetRealPathFromURI(Android.Net.Uri contentURI)
{
try
{
ICursor imageCursor = null;
string fullPathToImage = "";
imageCursor = ContentResolver.Query(contentURI, null, null, null, null);
imageCursor.MoveToFirst();
int idx = imageCursor.GetColumnIndex(MediaStore.Images.ImageColumns.Data);
if (idx != -1)
{
fullPathToImage = imageCursor.GetString(idx);
}
else
{
ICursor cursor = null;
var docID = DocumentsContract.GetDocumentId(contentURI);
var id = docID.Split(':')[1];
var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
var projections = new string[] { MediaStore.Images.ImageColumns.Data };
cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
if (cursor.Count == 0)
{
cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
}
var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
cursor.MoveToFirst();
fullPathToImage = cursor.GetString(colData);
}
return fullPathToImage;
}
catch (Exception ex)
{
Toast.MakeText(Xamarin.Forms.Forms.Context, "Unable to get path", ToastLength.Long).Show();
}
return null;
}
The extension(.png or .jpg) was missing not from the GetRealPathFromURI(), it happens in ImageHelpers.SaveFile(). So I save the filename to another variable from the path using Path.GetFileName() like below and pass the complete filename when call ImageHelpers.SaveFile().
var fileName = Path.GetFileName(picturepath);
I want to schedule multiple Tile Notifications while my app is running, so that when my app is in background, my schedule Tile notifications appear one by one using respective occurrence time.
But somehow when I schedule multiple (3) notifications only last one appears.
String message = "";
String key = "FamilyFarm" + count;
if (String.IsNullOrEmpty(duration) || String.IsNullOrEmpty(name))
return;
IsolatedStorageSettings setting = IsolatedStorageSettings.ApplicationSettings;
if (setting.Contains(key))
{
setting.Remove(key);
}
setting.Add(key, name);
count++;
ShellTileSchedule SampleTileSchedule = new ShellTileSchedule();
bool TileScheduleRunning = false;
// Update will happen one time.
SampleTileSchedule.Recurrence = UpdateRecurrence.Onetime;
// Start the update schedule now.
SampleTileSchedule.StartTime = DateTime.Now;
SampleTileSchedule.RemoteImageUri = new Uri(#"http://www.weather.gov/forecasts/graphical/images/conus/MaxT1_conus.png");
SampleTileSchedule.Start();
TileScheduleRunning = true;
ShellTile oTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("flip".ToString()));
if (oTile != null && oTile.NavigationUri.ToString().Contains("flip"))
{
FlipTileData oFliptile = new FlipTileData();
oFliptile.Title = name;
oFliptile.Count = 11;
oFliptile.BackTitle = key;
oFliptile.BackContent = name;
oFliptile.WideBackContent = name;
oFliptile.SmallBackgroundImage = new Uri("Assets/Tiles/FlipCycleTileMedium.png", UriKind.Relative);
oFliptile.BackgroundImage = new Uri("Assets/Tiles/FlipCycleTileLarge.png", UriKind.Relative);
oFliptile.WideBackgroundImage = new Uri("Assets/Tiles/Flip/FlipCycleTileLarge.png", UriKind.Relative);
oFliptile.BackBackgroundImage = new Uri("/Assets/Tiles/FlipCycleTileMedium.png", UriKind.Relative);
oFliptile.WideBackBackgroundImage = new Uri("/Assets/Tiles/FlipCycleTileMedium.png", UriKind.Relative);
oTile.Update(oFliptile);
// MessageBox.Show("Flip Tile Data successfully update.");
//return true;
}
else
{
// once it is created flip tile
Uri tileUri = new Uri("/MainPage.xaml?tile=flip", UriKind.Relative);
ShellTileData tileData = new FlipTileData()
{
Title = "Hello FamilyFarm",
BackTitle = key,
BackContent = name,
WideBackContent = name,
Count = 8,
SmallBackgroundImage = new Uri("/Assets/Tiles/FlipCycleTileMedium.png", UriKind.Relative),
BackgroundImage = new Uri("/Assets/Tiles/FlipCycleTileMedium.png", UriKind.Relative),
WideBackgroundImage = new Uri("/Assets/Tiles/FlipCycleTileMedium.png", UriKind.Relative),
};
ShellTile.Create(tileUri, tileData, true);
}
If you want to see the Tile Cycle, you should use
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207036(v=vs.105).aspx
or
Creating CycleTile with remote images
Otherwise if you want to see the Update taking place you should put a Thread.Sleep or Task.Wait between updates to be able to see them.
When you want some cycling in WP7.8 you can use MangoPollo.