C# Crystal Reports TimeZone - c#-4.0

I am using Crystal Reports ReportDocument object to load, run, and export a report to PDF. The report time is that of the web server. We have users running reports from different time zones. Is there a way to set the time zone of the report?
using (SqlCommand cmd = new SqlCommand(job.sproc, con))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (KeyValuePair<string, string> p in sprParams)
{
cmd.Parameters.AddWithValue(p.Key, p.Value);
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ReportDocument rpt = new ReportDocument();
rpt.Load(Path.Combine(RPT_LOCATION, job.repFileName));
rpt.Database.Tables[0].SetDataSource(ds.Tables[0]);
int i = 1;
foreach (string subReport in job.subReports)
{
using (ReportDocument srpt = rpt.OpenSubreport(subReport))
{
srpt.SetDataSource(ds.Tables[i++]);
}
}
ParameterFieldDefinitions parmFields = rpt.DataDefinition.ParameterFields;
ParameterValues pvals = new ParameterValues();
foreach (ParameterFieldDefinition def in parmFields)
{
if (!def.IsLinked())
{
ParameterDiscreteValue pval = new ParameterDiscreteValue();
if (rptParams.ContainsKey(def.Name))
{
pval.Value = rptParams[def.Name];
}
else
{
switch (def.ParameterValueKind)
{
case ParameterValueKind.BooleanParameter:
pval.Value = false;
break;
case ParameterValueKind.CurrencyParameter:
pval.Value = 0;
break;
case ParameterValueKind.DateParameter:
pval.Value = DateTime.Now.ToShortDateString();
break;
case ParameterValueKind.DateTimeParameter:
pval.Value = DateTime.Now;
break;
case ParameterValueKind.NumberParameter:
pval.Value = 0;
break;
case ParameterValueKind.TimeParameter:
pval.Value = DateTime.Now.ToShortTimeString();
break;
default:
pval.Value = String.Empty;
break;
}
}
pvals.Add(pval);
def.ApplyCurrentValues(pvals);
}
}
//save file
job.fileName = ExfiltrateReport(rpt, exfilType);
job.created = DateTime.UtcNow;
rpt.Dispose();
}

Related

PDF Digital Signing Disable CRL

I am writing a sample pdf signer using itextsharp.dll n the digital signature is on a usb device.
it's working nicely only problem is that some times the signing gets completely stops for hours together.
I have found that the signing process goes to digital issuer site to get CRL to embed in the signed document increasing it's size from 100kb to 1300kb+ and also signs document very slow due to getting CRL from issuer site.
but if I disable internet the file gets signed very fast and size increase is just 5-10kb.
So my question precisely is how can I instruct the signing process not to go online to get CRL n simply sign the document fast with less size increase in original document.
public void Sign(ICollection<X509Certificate> chain, X509Certificate2 pk,
String digestAlgorithm, CryptoStandard subfilter,
String reason, String location,
int estimatedSize)
{
IList<ICrlClient> crlList = new List<ICrlClient>();
crlList.Add(new CrlClientOnline(chain));
// Creating the reader and the stamper
PdfReader reader = null;
PdfStamper stamper = null;
FileStream os = null;
//int noofpdfs = 0;
var watch = Stopwatch.StartNew();
try
{
string[] srcfiles;
if (lblSplitedFilePath.Text.Equals("Split By Page Directory"))
srcfiles = Directory.GetFiles(tbsrcpath.Text, "*.pdf");
else
if (tbsrcpath.Text.ToUpper().Contains(#"\SPLIT"))
srcfiles = Directory.GetFiles(tbsrcpath.Text, "*.pdf");
else
srcfiles = Directory.GetFiles(tbsrcpath.Text + #"\split\", "*.pdf");
//int noofpdfs = srcfilePaths.Count();
for (int i = 0; i < srcfiles.Count(); i++)
{
// Get FileName
lblOutputFile.Text = tbtgtpath.Text + #"\" + Path.GetFileName(srcfiles[i]);
lblOutputFile.Refresh();
os = new FileStream(lblOutputFile.Text, FileMode.Create);
reader = new PdfReader(srcfiles[i]);
iTextSharp.text.Rectangle pdfbox = reader.GetPageSize(1);
stamper = PdfStamper.CreateSignature(reader, os, '\0');
// Creating the appearance
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
if (!string.IsNullOrWhiteSpace(tbContact.Text))
{
appearance.ReasonCaption = "Contact:";
appearance.Reason = tbContact.Text;// reason;
}
appearance.Location = location;
//Adding Image to Sign
if (cbAddImageSign.Checked)
{
var image = iTextSharp.text.Image.GetInstance(tbSignImage.Text);
appearance.Acro6Layers = true;
appearance.SignatureGraphic = image;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
}
int llx, lly, urx, ury;
int.TryParse(Tbllx.Text, out llx);
int.TryParse(tblly.Text, out lly);
int.TryParse(tburx.Text, out urx);
int.TryParse(tbury.Text, out ury);
pdfSigning.Properties.Settings.Default.llx = llx;
pdfSigning.Properties.Settings.Default.lly = lly;
pdfSigning.Properties.Settings.Default.urx = urx;
pdfSigning.Properties.Settings.Default.ury = ury;
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(llx, lly, urx, ury), 1, "sig");
//Add Water mark
if (!lblWaterMarkImagePath.Text.Equals("Pdf Water Mark Image Path"))
{
var wmimage = iTextSharp.text.Image.GetInstance(lblWaterMarkImagePath.Text);
wmimage.SetAbsolutePosition(0, 0);
wmimage.ScaleToFit(100, 100);
for (var j = 0; j < reader.NumberOfPages; j++)
{
var content = stamper.GetUnderContent(j + 1);
content.AddImage(wmimage);
}
}
//appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
// Creating the signature
try
{
IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
MakeSignature.SignDetached(appearance, pks, chain, crlList, null, null, estimatedSize,
subfilter);
}
catch (CryptographicException ex)
{
MessageBox.Show(ex.ToString());
}
//noofpdfs++;
if (cbPrintOnSign.Checked)
{
switch (tbPrintMethod.Text)
{
case "2":
SendFileToPrinter(lblOutputFile.Text, printpdf2printer);
break;
default:
SendToPrinter(lblOutputFile.Text);
break;
}
}
if (cbDeletePdfPostSign.Checked)
{
File.Delete(srcfiles[i]);
}
dgvPrintFiles.Rows.Add(srcfiles[i].ToString());
}
lblOutputFile.Text += #" Siging Over:Signed " + srcfiles.Count().ToString() + " Files";
}
finally
{
if (reader != null)
reader.Close();
if (stamper != null)
stamper.Close();
if (os != null)
os.Close();
}
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
MessageBox.Show("Signing Time:" + elapsedMs / 1000 + " Second");
}

Command Timeout, longer to get response back

I am executing large query,so my app throwing time out error. Some of the thread suggested to added command time out but after adding those lines it take longer to get response back, any idea why or what am i missing in my code?
public int CreateRecord(string theCommand, DataSet theInputData)
{
int functionReturnValue = 0;
int retVal = 0;
SqlParameter objSqlParameter = default(SqlParameter);
DataSet dsParameter = new DataSet();
int i = 0;
try
{
//Set the command text (stored procedure name or SQL statement).
mobj_SqlCommand.CommandTimeout = 120;
mobj_SqlCommand.CommandText = theCommand;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
for (i = 0; i <= (theInputData.Tables.Count - 1); i++)
{
if (theInputData.Tables[i].Rows.Count > 0)
{
dsParameter.Tables.Add(theInputData.Tables[i].Copy());
}
}
objSqlParameter = new SqlParameter("#theXmlData", SqlDbType.Text);
objSqlParameter.Direction = ParameterDirection.Input;
objSqlParameter.Value = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + dsParameter.GetXml();
//Attach to the parameter to mobj_SqlCommand.
mobj_SqlCommand.Parameters.Add(objSqlParameter);
//Finally, execute the command.
retVal = (int)mobj_SqlCommand.ExecuteScalar();
//Detach the parameters from mobj_SqlCommand, so it can be used again.
mobj_SqlCommand.Parameters.Clear();
functionReturnValue = retVal;
}
catch (Exception ex)
{
throw new System.Exception(ex.Message);
}
finally
{
//Clean up the objects created in this object.
if (mobj_SqlConnection.State == ConnectionState.Open)
{
mobj_SqlConnection.Close();
mobj_SqlConnection.Dispose();
mobj_SqlConnection = null;
}
if ((mobj_SqlCommand != null))
{
mobj_SqlCommand.Dispose();
mobj_SqlCommand = null;
}
if ((mobj_SqlDataAdapter != null))
{
mobj_SqlDataAdapter.Dispose();
mobj_SqlDataAdapter = null;
}
if ((dsParameter != null))
{
dsParameter.Dispose();
dsParameter = null;
}
objSqlParameter = null;
}
return functionReturnValue;
}

Why is parallel.Invoke not working in this case

I have an array of files like this..
string[] unZippedFiles;
the idea is that I want to parse these files in paralle. As they are parsed a record gets placed on a concurrentbag. As record is getting placed I want to kick of the update function.
Here is what I am doing in my Main():
foreach(var file in unZippedFiles)
{ Parallel.Invoke
(
() => ImportFiles(file),
() => UpdateTest()
);
}
this is what the code of Update loooks like.
static void UpdateTest( )
{
Console.WriteLine("Updating/Inserting merchant information.");
while (!merchCollection.IsEmpty || producingRecords )
{
merchant x;
if (merchCollection.TryTake(out x))
{
UPDATE_MERCHANT(x.m_id, x.mInfo, x.month, x.year);
}
}
}
This is what the import code looks like. It's pretty much a giant string parser.
System.IO.StreamReader SR = new System.IO.StreamReader(fileName);
long COUNTER = 0;
StringBuilder contents = new StringBuilder( );
string M_ID = "";
string BOF_DELIMITER = "%%MS_SKEY_0000_000_PDF:";
string EOF_DELIMITER = "%%EOF";
try
{
record_count = 0;
producingRecords = true;
for (COUNTER = 0; COUNTER <= SR.BaseStream.Length - 1; COUNTER++)
{
if (SR.EndOfStream)
{
break;
}
contents.AppendLine(Strings.Trim(SR.ReadLine()));
contents.AppendLine(System.Environment.NewLine);
//contents += Strings.Trim(SR.ReadLine());
//contents += Strings.Chr(10);
if (contents.ToString().IndexOf((EOF_DELIMITER)) > -1)
{
if (contents.ToString().StartsWith(BOF_DELIMITER) & contents.ToString().IndexOf(EOF_DELIMITER) > -1)
{
string data = contents.ToString();
M_ID = data.Substring(data.IndexOf("_M") + 2, data.Substring(data.IndexOf("_M") + 2).IndexOf("_"));
Console.WriteLine("Merchant: " + M_ID);
merchant newmerch;
newmerch.m_id = M_ID;
newmerch.mInfo = data.Substring(0, (data.IndexOf(EOF_DELIMITER) + 5));
newmerch.month = DateTime.Now.AddMonths(-1).Month;
newmerch.year = DateTime.Now.AddMonths(-1).Year;
//Update(newmerch);
merchCollection.Add(newmerch);
}
contents.Clear();
//GC.Collect();
}
}
SR.Close();
// UpdateTest();
}
catch (Exception ex)
{
producingRecords = false;
}
finally
{
producingRecords = false;
}
}
the problem i am having is that the Update runs once and then the importfile function just takes over and does not yield to the update function. Any ideas on what am I doing wrong would be of great help.
Here's my stab at fixing your thread synchronisation. Note that I haven't changed any of the code from the functional standpoint (with the exception of taking out the catch - it's generally a bad idea; exceptions need to be propagated).
Forgive if something doesn't compile - I'm writing this based on incomplete snippets.
Main
foreach(var file in unZippedFiles)
{
using (var merchCollection = new BlockingCollection<merchant>())
{
Parallel.Invoke
(
() => ImportFiles(file, merchCollection),
() => UpdateTest(merchCollection)
);
}
}
Update
private void UpdateTest(BlockingCollection<merchant> merchCollection)
{
Console.WriteLine("Updating/Inserting merchant information.");
foreach (merchant x in merchCollection.GetConsumingEnumerable())
{
UPDATE_MERCHANT(x.m_id, x.mInfo, x.month, x.year);
}
}
Import
Don't forget to pass in merchCollection as a parameter - it should not be static.
System.IO.StreamReader SR = new System.IO.StreamReader(fileName);
long COUNTER = 0;
StringBuilder contents = new StringBuilder( );
string M_ID = "";
string BOF_DELIMITER = "%%MS_SKEY_0000_000_PDF:";
string EOF_DELIMITER = "%%EOF";
try
{
record_count = 0;
for (COUNTER = 0; COUNTER <= SR.BaseStream.Length - 1; COUNTER++)
{
if (SR.EndOfStream)
{
break;
}
contents.AppendLine(Strings.Trim(SR.ReadLine()));
contents.AppendLine(System.Environment.NewLine);
//contents += Strings.Trim(SR.ReadLine());
//contents += Strings.Chr(10);
if (contents.ToString().IndexOf((EOF_DELIMITER)) > -1)
{
if (contents.ToString().StartsWith(BOF_DELIMITER) & contents.ToString().IndexOf(EOF_DELIMITER) > -1)
{
string data = contents.ToString();
M_ID = data.Substring(data.IndexOf("_M") + 2, data.Substring(data.IndexOf("_M") + 2).IndexOf("_"));
Console.WriteLine("Merchant: " + M_ID);
merchant newmerch;
newmerch.m_id = M_ID;
newmerch.mInfo = data.Substring(0, (data.IndexOf(EOF_DELIMITER) + 5));
newmerch.month = DateTime.Now.AddMonths(-1).Month;
newmerch.year = DateTime.Now.AddMonths(-1).Year;
//Update(newmerch);
merchCollection.Add(newmerch);
}
contents.Clear();
//GC.Collect();
}
}
SR.Close();
// UpdateTest();
}
finally
{
merchCollection.CompleteAdding();
}
}

Programmatically Set a QueryStringFilterWebPart / ExcelWebRenderer Connection

Code:
public static void ChartPageConnector(SPWeb web, string pageURL, string providerWpId, string consumerWpId, string mappedName)
{
SPFile file = web.Files[pageURL];
SPLimitedWebPartManager mgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
TransformableFilterValuesToFilterValuesTransformer transformer = new TransformableFilterValuesToFilterValuesTransformer();
transformer.MappedConsumerParameterName = mappedName;
//QueryStringFilterWebPart provider = (QueryStringFilterWebPart)mgr.WebParts[providerWpId];
//ExcelWebRenderer consumer = (ExcelWebRenderer)mgr.WebParts[consumerWpId];
JWP.WebPart provider = mgr.WebParts[providerWpId];
JWP.WebPart consumer = mgr.WebParts[consumerWpId];
ProviderConnectionPoint pcp = null;
foreach (ProviderConnectionPoint ppoint in mgr.GetProviderConnectionPoints(provider))
{
if (ppoint.InterfaceType ==
typeof(Microsoft.SharePoint.WebPartPages.ITransformableFilterValues))
{
pcp = ppoint;
break;
}
}
ConsumerConnectionPoint ccp = null;
foreach (ConsumerConnectionPoint cpoint in mgr.GetConsumerConnectionPoints(consumer))
{
if (cpoint.InterfaceType == typeof(IFilterValues))
{
ccp = cpoint;
break;
}
}
//mgr.SPConnectWebParts(provider, pcp, consumer, ccp);
mgr.SPConnectWebParts(provider, pcp, consumer, ccp, transformer);
file.Update();
web.Update();
}
Error:
The connection point "IFilterValues" on "g_33d68e82_6478_4629_a079_5a7e02ac4695" is disabled.
Any Ideas Why?

How do I programmatically create a FTP site in IIS7 on Windows7?

I am looking to do this step: 'Creating a New FTP Site by Editing the IIS 7.0 Configuration Files' with a batch file and was wondering if anybody has done this already?
http://learn.iis.net/page.aspx/301/creating-a-new-ftp-site/
Try this. You need to reference the COM component "AppHostAdminLibrary"
using AppHostAdminLibrary;
...
public void AddFtp7Site(String siteName, String siteId, String siteRoot) {
String configPath;
String configSectionName;
var fNewSite = false;
var fNewApplication = false;
var fNewVDir = false;
//
// First setup the sites section
//
configPath = "MACHINE/WEBROOT/APPHOST";
configSectionName = "system.applicationHost/sites";
var adminManager = new AppHostAdminLibrary.AppHostWritableAdminManager();
adminManager.CommitPath = configPath;
try {
var sitesElement = adminManager.GetAdminSection(configSectionName, configPath);
IAppHostElement newSiteElement = null;
//
// check if site already exists
//
for (var i = 0; i < sitesElement.Collection.Count; i++) {
var siteElement = sitesElement.Collection[i];
if (siteElement.Properties["name"].Value.Equals(siteName) &&
siteElement.Properties["id"].Value.Equals(siteId)) {
newSiteElement = siteElement;
break;
}
}
if (newSiteElement == null) {
//
// Site doesn't exist yet. Add new site node
//
newSiteElement = sitesElement.Collection.CreateNewElement("");
newSiteElement.Properties["id"].Value = siteId;
newSiteElement.Properties["name"].Value = siteName;
fNewSite = true;
}
// setup bindings for the new site
var ftpBindingString = "*:21:";
var Bindings = newSiteElement.GetElementByName("bindings");
var BindingElement = Bindings.Collection.CreateNewElement("");
BindingElement.Properties["protocol"].Value = "ftp";
BindingElement.Properties["bindingInformation"].Value = ftpBindingString;
try {
Bindings.Collection.AddElement(BindingElement, 0);
}
catch (Exception ex) {
if (ex.Message != "") // ERROR_ALREADY_EXISTS ?
{
throw;
}
}
IAppHostElement newApplication = null;
//
// check if root application already exists
//
for (var i = 0; i < newSiteElement.Collection.Count; i++) {
var applicationElement = newSiteElement.Collection[i];
if (applicationElement.Properties["path"].Value.Equals("/")) {
newApplication = applicationElement;
break;
}
}
if (newApplication == null) {
newApplication = newSiteElement.Collection.CreateNewElement("application");
newApplication.Properties["path"].Value = "/";
fNewApplication = true;
}
IAppHostElement newVirtualDirectory = null;
//
// search for the root vdir
//
for (var i = 0; i < newApplication.Collection.Count; i++) {
var vdirElement = newApplication.Collection[i];
if (vdirElement.Properties["path"].Value.Equals("/")) {
newVirtualDirectory = vdirElement;
break;
}
}
if (newVirtualDirectory == null) {
newVirtualDirectory = newApplication.Collection.CreateNewElement("");
newVirtualDirectory.Properties["path"].Value = "/";
fNewVDir = true;
}
newVirtualDirectory.Properties["physicalPath"].Value = siteRoot;
if (fNewVDir) {
newApplication.Collection.AddElement(newVirtualDirectory, 0);
}
if (fNewApplication) {
newSiteElement.Collection.AddElement(newApplication, 0);
}
var ftpSiteSettings = newSiteElement.GetElementByName("ftpServer").GetElementByName("security").GetElementByName("authentication");
Console.WriteLine("Enable anonymous authentication");
var anonAuthSettings = ftpSiteSettings.GetElementByName("anonymousAuthentication");
anonAuthSettings.Properties["enabled"].Value = "true";
Console.WriteLine("Disable basic authentication");
var basicAuthSettings = ftpSiteSettings.GetElementByName("basicAuthentication");
basicAuthSettings.Properties["enabled"].Value = "false";
BindingElement.Properties["bindingInformation"].Value = "*:21:";
//
// Time to add new site element and commit changes
//
if (fNewSite) {
sitesElement.Collection.AddElement(newSiteElement, 0);
}
adminManager.CommitChanges();
}
catch (Exception ex) {
Console.WriteLine("Error occured in AddDefaultFtpSite: " + ex.Message);
}
//
// Add <authorization> section to allow everyone Read
//
Console.WriteLine("Enable everyone Read access");
try {
configPath = "MACHINE/WEBROOT/APPHOST/" + siteName;
configSectionName = "system.ftpServer/security/authorization";
var azSection = adminManager.GetAdminSection(configSectionName, configPath);
azSection.Collection.Clear();
var newAzElement = azSection.Collection.CreateNewElement("");
newAzElement.Properties["accessType"].Value = "Allow";
newAzElement.Properties["users"].Value = "*";
newAzElement.Properties["permissions"].Value = "Read";
azSection.Collection.AddElement(newAzElement, 0);
adminManager.CommitChanges();
}
catch (Exception ex) {
Console.WriteLine("Error occured while adding authorization section: " + ex.Message);
}
}
Does this help?:
http://blogs.iis.net/jaroslad/archive/2007/06/13/how-to-programatically-create-an-ftp7-site.aspx

Resources