repeatedly call AddImageUrl(url) to assemble pdf document - asp.net

I'm using abcpdf and I'm curious if we can we recursively call AddImageUrl() function to assemble pdf document that compile multiple urls?
something like:
int pageCount = 0;
int theId = theDoc.AddImageUrl("http://stackoverflow.com/search?q=abcpdf+footer+page+x+out+of+", true, 0, true);
//assemble document
while (theDoc.Chainable(theId))
{
theDoc.Page = theDoc.AddPage();
theId = theDoc.AddImageToChain(theId);
}
pageCount = theDoc.PageCount;
Console.WriteLine("1 document page count:" + pageCount);
//Flatten document
for (int i = 1; i <= pageCount; i++)
{
theDoc.PageNumber = i;
theDoc.Flatten();
}
//now try again
theId = theDoc.AddImageUrl("http://stackoverflow.com/questions/1980890/pdf-report-generation", true, 0, true);
//assemble document
while (theDoc.Chainable(theId))
{
theDoc.Page = theDoc.AddPage();
theId = theDoc.AddImageToChain(theId);
}
Console.WriteLine("2 document page count:" + theDoc.PageCount);
//Flatten document
for (int i = pageCount + 1; i <= theDoc.PageCount; i++)
{
theDoc.PageNumber = i;
theDoc.Flatten();
}
pageCount = theDoc.PageCount;
edit:
code that seems to work based on 'hunter' solution:
static void Main(string[] args)
{
Test2();
}
static void Test2()
{
Doc theDoc = new Doc();
// Set minimum number of items a page of HTML should contain.
theDoc.HtmlOptions.ContentCount = 10;// Otherwise the page will be assumed to be invalid.
theDoc.HtmlOptions.RetryCount = 10; // Try to obtain html page 10 times
theDoc.HtmlOptions.Timeout = 180000;// The page must be obtained in less then 10 seconds
theDoc.Rect.Inset(0, 10); // set up document
theDoc.Rect.Position(5, 15);
theDoc.Rect.Width = 602;
theDoc.Rect.Height = 767;
theDoc.HtmlOptions.PageCacheEnabled = false;
IList<string> urls = new List<string>();
urls.Add("http://stackoverflow.com/search?q=abcpdf+footer+page+x+out+of+");
urls.Add("http://stackoverflow.com/questions/1980890/pdf-report-generation");
urls.Add("http://yahoo.com");
urls.Add("http://stackoverflow.com/questions/4338364/recursively-call-addimageurlurl-to-assemble-pdf-document");
foreach (string url in urls)
AddImage(ref theDoc, url);
//Flatten document
for (int i = 1; i <= theDoc.PageCount; i++)
{
theDoc.PageNumber = i;
theDoc.Flatten();
}
theDoc.Save("batchReport.pdf");
theDoc.Clear();
Console.Read();
}
static void AddImage(ref Doc theDoc, string url)
{
int theId = theDoc.AddImageUrl(url, true, 0, true);
while (theDoc.Chainable(theId))
{
theDoc.Page = theDoc.AddPage();
theId = theDoc.AddImageToChain(theId); // is this right?
}
Console.WriteLine(string.Format("document page count: {0}", theDoc.PageCount.ToString()));
}
edit 2:unfortunately calling AddImageUrl multiple times when generating pdf documents doesn't seem to work...

Finally found reliable solution.
Instead of executing AddImageUrl() function on the same underlying document, we should execute AddImageUrl() function on it's own Doc document and build collection of documents that at the end we will assemble into one document using Append() method.
Here is the code:
static void Main(string[] args)
{
Test2();
}
static void Test2()
{
Doc theDoc = new Doc();
var urls = new Dictionary<int, string>();
urls.Add(1, "http://www.asp101.com/samples/server_execute_aspx.asp");
urls.Add(2, "http://stackoverflow.com/questions/4338364/repeatedly-call-addimageurlurl-to-assemble-pdf-document");
urls.Add(3, "http://www.google.ca/");
urls.Add(4, "http://ca.yahoo.com/?p=us");
var theDocs = new List<Doc>();
foreach (int key in urls.Keys)
theDocs.Add(GetReport(urls[key]));
foreach (var doc in theDocs)
{
if (theDocs.IndexOf(doc) == 0)
theDoc = doc;
else
theDoc.Append(doc);
}
theDoc.Save("batchReport.pdf");
theDoc.Clear();
Console.Read();
}
static Doc GetReport(string url)
{
Doc theDoc = new Doc();
// Set minimum number of items a page of HTML should contain.
theDoc.HtmlOptions.ContentCount = 10;// Otherwise the page will be assumed to be invalid.
theDoc.HtmlOptions.RetryCount = 10; // Try to obtain html page 10 times
theDoc.HtmlOptions.Timeout = 180000;// The page must be obtained in less then 10 seconds
theDoc.Rect.Inset(0, 10); // set up document
theDoc.Rect.Position(5, 15);
theDoc.Rect.Width = 602;
theDoc.Rect.Height = 767;
theDoc.HtmlOptions.PageCacheEnabled = false;
int theId = theDoc.AddImageUrl(url, true, 0, true);
while (theDoc.Chainable(theId))
{
theDoc.Page = theDoc.AddPage();
theId = theDoc.AddImageToChain(theId);
}
//Flatten document
for (int i = 1; i <= theDoc.PageCount; i++)
{
theDoc.PageNumber = i;
theDoc.Flatten();
}
return theDoc;
}
}

Related

GWT read mime type client side

I'm trying to read the mime type in GWT client side in order to validate a file before upload it. To do this I use JSNI to read the file header using HTML5 filereader API. However my problem is that GWT does not wait for the result of the reading and continue the code execution. The side effect is that my boolean is not set yet and my condition goes wrong. Is there any mechanism like promise implemented in GWT?
Any help on this would be much appreciated!
UploadImageButtonWidget.java
private boolean isMimeTypeValid = false;
private String mimeType = null;
public native boolean isValid(Element element)/*-{
var widget = this;
var files = element.files;
var reader = new FileReader();
var CountdownLatch = function (limit){
this.limit = limit;
this.count = 0;
this.waitBlock = function (){};
};
CountdownLatch.prototype.countDown = function (){
this.count = this.count + 1;
if(this.limit <= this.count){
return this.waitBlock();
}
};
CountdownLatch.prototype.await = function(callback){
this.waitBlock = callback;
};
var barrier = new CountdownLatch(1);
reader.readAsArrayBuffer(files[0]);
reader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
widget.#com.portal.client.widgets.base.UploadImageButtonWidget::setMimeType(Ljava/lang/String;)(header);
barrier.countDown();
}
return barrier.await(function(){
return widget.#com.portal.client.widgets.base.UploadImageButtonWidget::isMimeTypeValid();
});
}-*/
public void setMimeType(String headerString) {
boolean mimeValid = true;
if (headerString.equalsIgnoreCase(PNG_HEADER)) {
mimeType = PNG_MIMETYPE;
} else if (headerString.equalsIgnoreCase(GIF_HEADER)) {
mimeType = GIF_MIMETYPE;
} else if (headerString.equalsIgnoreCase(JPG_HEADER1) || headerString.equalsIgnoreCase(JPG_HEADER2) || headerString.equalsIgnoreCase(JPG_HEADER3)) {
mimeType = JPG_MIMETYPE;
} else {
mimeValid = false;
setValidationError(i18n.uploadErrorNotImageBasedOnMimeType());
fileChooser.getElement().setPropertyJSO("files", null);
setErrorStatus();
}
setMimeTypeValid(mimeValid);
}
public boolean isMimeTypeValid() {
GWT.log("mimeType" + mimeType);
GWT.log("isMimetypeValid" + String.valueOf(isMimeTypeValid));
return mimeType != null;
}
in the activity:
public void validateAndUpload() {
UploadImageButtonWidget uploadImageButtonWidget = view.getUpload();
if (uploadImageButtonWidget.isValid()) {
GWT.log("mime ok: will be uploaded");
uploadImage();
} else {
GWT.log("mime not ok: will not be uploaded");
}
}

SMPP message length error using jamaa more than 160 characters

I am using jamaa-smpp to send sms. But I am not able to send more than 160 characters using the api. I am using the following link http://jamaasmpp.codeplex.com/
The code is as follows
SmppConnectionProperties properties = _client.Properties;
properties.SystemID = "test";
properties.Password = "test1";
properties.Port = 101; //IP port to use
properties.Host = "..."; //SMSC host name or IP Address
....
Is it possible to send more than 160 character using that API.
I found the solution it was there on the website discussion. I am posting it here so that one can find solution here.
I replaced the existing function in the TextMessage.cs (JamaaTech.Smpp.Net.Client).
The function name is IEnumerable<SendSmPDU> GetPDUs(DataCoding defaultEncoding)
//protected override IEnumerable<SendSmPDU> GetPDUs(DataCoding defaultEncoding)
//{
// //This smpp implementation does not support sending concatenated messages,
// //however, concatenated messages are supported on the receiving side.
// int maxLength = GetMaxMessageLength(defaultEncoding, false);
// byte[] bytes = SMPPEncodingUtil.GetBytesFromString(vText, defaultEncoding);
// //Check message size
// if(bytes.Length > maxLength)
// {
// throw new InvalidOperationException(string.Format(
// "Encoding '{0}' does not support messages of length greater than '{1}' charactors",
// defaultEncoding, maxLength));
// }
// SubmitSm sm = new SubmitSm();
// sm.SetMessageBytes(bytes);
// sm.SourceAddress.Address = vSourceAddress;
// sm.DestinationAddress.Address = vDestinatinoAddress;
// sm.DataCoding = defaultEncoding;
// if (vRegisterDeliveryNotification) { sm.RegisteredDelivery = RegisteredDelivery.DeliveryReceipt; }
// yield return sm;
//}
protected override IEnumerable<SendSmPDU> GetPDUs(DataCoding defaultEncoding)
{
SubmitSm sm = new SubmitSm();
sm.SourceAddress.Address = vSourceAddress;
sm.DestinationAddress.Address = vDestinatinoAddress;
sm.DataCoding = defaultEncoding;
if (vRegisterDeliveryNotification)
sm.RegisteredDelivery = RegisteredDelivery.DeliveryReceipt;
int maxLength = GetMaxMessageLength(defaultEncoding, false);
byte[] bytes = SMPPEncodingUtil.GetBytesFromString(vText, defaultEncoding);
if (bytes.Length > maxLength)
{
var SegID = new Random().Next(1000, 9999);
var messages = Split(vText, GetMaxMessageLength(defaultEncoding, true));
var totalSegments = messages.Count;
var udh = new Udh(SegID, totalSegments, 0);
for (int i = 0; i < totalSegments; i++)
{
udh.MessageSequence = i + 1;
sm.Header.SequenceNumber = PDUHeader.GetNextSequenceNumber();
sm.SetMessageText(messages[i], defaultEncoding, udh);
yield return sm;
}
}
else
{
sm.SetMessageBytes(bytes);
yield return sm;
}
}
private static List<String> Split(string message, int maxPartLength)
{
var result = new List<String>();
for (int i = 0; i < message.Length; i += maxPartLength)
{
var chunkSize = i + maxPartLength < message.Length ? maxPartLength : message.Length - i;
var chunk = new char[chunkSize];
message.CopyTo(i, chunk, 0, chunkSize);
result.Add(new string(chunk));
}
return result;
}

How to signal waithandle.waitany when doing async requests?

I'm using the following sample code to fetch some HTML Pages using async requests.
I don't want to wait until every request is completed that is using WaitHandle.WaitAll, just until the correct value is found. I'm currently doing it this way, but it feels wrong to send ManualResetEvents to the thread. Is it how it should be done? Is there a better way?
public static void runprogram()
{
System.Net.ServicePointManager.DefaultConnectionLimit = 20;
FetchPageDelegate del = new FetchPageDelegate(FetchPage);
List<HtmlDocument> htmllist = new List<HtmlDocument>();
List<IAsyncResult> results = new List<IAsyncResult>();
List<WaitHandle> waitHandles = new List<WaitHandle>();
List<ManualResetEvent> handles = new List<ManualResetEvent>();
for (int i = 0; i < 20; i++)
{
ManualResetEvent e = new ManualResetEvent(false);
handles.Add(e);
}
for(int i = 0; i < 200; i += 10)
{
int y = 0;
string url = #"URLTOPARSE" + i;
IAsyncResult result = del.BeginInvoke(url, handles[y], null, null);
results.Add(result);
waitHandles.Add(result.AsyncWaitHandle);
y++;
}
//Here i check for a signal
WaitHandle.WaitAny(handles.ToArray());
//WaitHandle.WaitAll(waitHandles.ToArray());
foreach (IAsyncResult async in results)
{
FetchPageDelegate delle = (async as AsyncResult).AsyncDelegate as FetchPageDelegate;
HtmlDocument htm = delle.EndInvoke(async);
if(htm.DocumentNode.InnerHtml.Contains("ANYTHING TO CHECK FOR(ONLY A TEST"))
{
return;
}
}
}

Use MatchPattern property of FindMatchingFiles workflow activity

I'm customizing the default workflow of build process template using TFS 2010 Team Build. There is an activity named FindMatchingFiles allows to search for specific files with a pattern defined in MatchPattern property. It works if I only specify one file extension. Example:
String.Format("{0}\\**\\\*.msi", SourcesDirectory)
But I would like to include *.exe as well. Trying following pattern but it doesn't work:
String.Format("{0}\\**\\\*.(msi|exe)", SourcesDirectory)
Anyone could show me how to correct it?
You can use String.Format("{0}\**\*.msi;{0}\**\*.exe", SourcesDirectory)
The FindMatchingFiles activity's MatchPattern property uses the
Syntax that is supported by the searchPattern argument of the Directory.GetFiles(String, String) method.
That means that you can't combine multiple extensions. You'll need to call the FindMatchingFiles activity twice. You can then combine the results of those two calls when you use them (i.e. if your results are msiFiles and exeFiles, you can use msiFiles.Concat(exeFiles) as the input to a ForEach).
However, as you can see with #antwoord's answer, the activity does actually seem to accept a semi-colon delimited list of patterns, unlike Directory.GetFiles.
FindMatchingFiles has some strange search pattern. Here is the code (decompiled using ILSpy) so you can test your search patterns without having to kick off a new build.
It contains a hardcoded root dir at the following location (Z:)
List<string> matchingDirectories = GetMatchingDirectories(#"Z:", matchPattern.Substring(0, num), 0);
Code:
using System;
using System.Collections.Generic;
using System.IO;
namespace DirectoryGetFiles
{
//// Use the FindMatchingFiles activity to find files. Specify the search criteria in the MatchPattern (String) property.
//// In this property, you can specify an argument that includes the following elements:
//// Syntax that is supported by the searchPattern argument of the Directory GetFiles(String, String) method.
////
//// ** to specify a recursive search. For example:
//// To search the sources directory for text files, you could specify something that resembles the following
//// value for the MatchPattern property: String.Format("{0}\**\*.txt", SourcesDirectory).
////
//// To search the sources directory for text files in one or more subdirectories that are called txtfiles,
//// you could specify something that resembles the following value for the MatchPattern property:
//// String.Format("{0}\**\txtfiles\*.txt", SourcesDirectory).
class Program
{
static void Main(string[] args)
{
string searchPattern = #"_PublishedWebsites\Web\Scripts\jasmine-specs**\*.js";
var results = Execute(searchPattern);
foreach (var i in results)
{
Console.WriteLine("found: {0}", i);
}
Console.WriteLine("Done...");
Console.ReadLine();
}
private static IEnumerable<string> Execute(string pattern)
{
string text = pattern;
text = text.Replace(";;", "\0");
var hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
string[] array = text.Split(new char[]
{
';'
}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < array.Length; i++)
{
string text2 = array[i];
string text3 = text2.Replace("\0", ";");
if (IsValidPattern(text3))
{
List<string> list = ComputeMatchingPaths(text3);
if (list.Count > 0)
{
using (List<string>.Enumerator enumerator = list.GetEnumerator())
{
while (enumerator.MoveNext())
{
string current = enumerator.Current;
hashSet.Add(current);
}
goto IL_15C;
}
}
////Message = ActivitiesResources.Format("NoMatchesForSearchPattern", new object[]
}
else
{
//// Message = ActivitiesResources.Format("InvalidSearchPattern", new object[]
}
IL_15C: ;
}
return hashSet;//.OrderBy((string x) => x, FileSpec.TopDownComparer);
}
private static bool IsValidPattern(string pattern)
{
string text = "**" + Path.DirectorySeparatorChar;
int num = pattern.IndexOf(text, StringComparison.Ordinal);
return (num < 0 || (pattern.IndexOf(text, num + text.Length, StringComparison.OrdinalIgnoreCase) <= 0 && pattern.IndexOf(Path.DirectorySeparatorChar, num + text.Length) <= 0)) && pattern[pattern.Length - 1] != Path.DirectorySeparatorChar;
}
private static List<string> ComputeMatchingPaths(string matchPattern)
{
List<string> list = new List<string>();
string text = "**" + Path.DirectorySeparatorChar;
int num = matchPattern.IndexOf(text, 0, StringComparison.OrdinalIgnoreCase);
if (num >= 0)
{
List<string> matchingDirectories = GetMatchingDirectories(#"Z:", matchPattern.Substring(0, num), 0);
string searchPattern = matchPattern.Substring(num + text.Length);
using (List<string>.Enumerator enumerator = matchingDirectories.GetEnumerator())
{
while (enumerator.MoveNext())
{
string current = enumerator.Current;
list.AddRange(Directory.GetFiles(current, searchPattern, SearchOption.AllDirectories));
}
return list;
}
}
int num2 = matchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (num2 >= 0)
{
List<string> matchingDirectories2 = GetMatchingDirectories(string.Empty, matchPattern.Substring(0, num2 + 1), 0);
string searchPattern2 = matchPattern.Substring(num2 + 1);
using (List<string>.Enumerator enumerator2 = matchingDirectories2.GetEnumerator())
{
while (enumerator2.MoveNext())
{
string current2 = enumerator2.Current;
try
{
list.AddRange(Directory.GetFiles(current2, searchPattern2, SearchOption.TopDirectoryOnly));
}
catch
{
}
}
return list;
}
}
try
{
list.AddRange(Directory.GetFiles(Directory.GetCurrentDirectory(), matchPattern, SearchOption.TopDirectoryOnly));
}
catch
{
}
return list;
}
private static List<string> GetMatchingDirectories(string rootDir, string pattern, int level)
{
if (level > 129)
{
return new List<string>();
}
List<string> list = new List<string>();
int num = pattern.IndexOf('*');
if (num >= 0)
{
int num2 = pattern.Substring(0, num).LastIndexOf(Path.DirectorySeparatorChar);
string text = (num2 >= 0) ? Path.Combine(rootDir, pattern.Substring(0, num2 + 1)) : rootDir;
if (text.Equals(string.Empty))
{
text = Directory.GetCurrentDirectory();
}
int num3 = pattern.IndexOf(Path.DirectorySeparatorChar, num);
if (num3 < 0)
{
num3 = pattern.Length;
}
string searchPattern = pattern.Substring(num2 + 1, num3 - num2 - 1);
try
{
string[] directories = Directory.GetDirectories(text, searchPattern, SearchOption.TopDirectoryOnly);
if (num3 < pattern.Length - 1)
{
string pattern2 = pattern.Substring(num3 + 1);
string[] array = directories;
for (int i = 0; i < array.Length; i++)
{
string rootDir2 = array[i];
list.AddRange(GetMatchingDirectories(rootDir2, pattern2, level + 1));
}
}
else
{
list.AddRange(directories);
}
return list;
}
catch
{
return list;
}
}
string text2 = Path.Combine(rootDir, pattern);
if (text2.Equals(string.Empty))
{
list.Add(Directory.GetCurrentDirectory());
}
else
{
if (Directory.Exists(text2))
{
list.Add(Path.GetFullPath(text2));
}
}
return list;
}
}
}

Cannot add an entity that already exists

Code:
public ActionResult Create(Group group)
{
if (ModelState.IsValid)
{
group.int_CreatedBy = 1;
group.dtm_CreatedDate = DateTime.Now;
var Groups = Request["Groups"];
int GroupId = 0;
GroupFeature GroupFeature=new GroupFeature();
foreach (var GroupIdd in Groups)
{
// GroupId = int.Parse(GroupIdd.ToString());
}
var Features = Request["Features"];
int FeatureId = 0;
int t = 0;
int ids=0;
string[] Feature = Features.Split(',').ToArray();
//foreach (var FeatureIdd in Features)
for(int i=0; i<Feature.Length; i++)
{
if (int.TryParse(Feature[i].ToString(), out ids))
{
GroupFeature.int_GroupId = 35;
GroupFeature.int_FeaturesId = ids;
if (ids != 0)
{
GroupFeatureRepository.Add(GroupFeature);
GroupFeatureRepository.Save();
}
}
}
return RedirectToAction("Details", new { id = group.int_GroupId });
}
return View();
}
I am getting an error here Cannot add an entity that already exists. at this line GroupFeatureRepository.Add(GroupFeature);
GroupFeatureRepository.Save();
This line:
GroupFeature GroupFeature=new GroupFeature();
needs to be inside your for loop, like this:
for(int i=0; i<Feature.Length; i++)
{
if (int.TryParse(Feature[i].ToString(), out ids))
{
GroupFeature GroupFeature=new GroupFeature();
You need to add a new GroupFeature each time(e.g. one not in that collection, which your re-used object already is after the first loop). You can't re-use the same GroupFeature object like that for adding, but moving it inside the loop so you generate a distinct GroupFeature each time will resolve this.

Resources