PayPal Order Total and Item Total issues on ExpressCheckout - paypal

I have a working expressCheckout process, and all works well until i try to multiply the amounts by a given exchange rate.
Here are the 2 versions (1st, the working version with no exchange rate, 2nd the non working version with the implementation of the exchange rate:
Workign version
Imports PayPal.PayPalAPIInterfaceService.Model
Imports PayPal.PayPalAPIInterfaceService
Imports PayPal.Manager
Partial Class paypalExpressCheckout
Inherits System.Web.UI.Page
Dim currentPreSale As New PreSale
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Session("ShoppingCartDT") Is Nothing Then
currentPreSale = Session("currentPreSale")
Dim request As New SetExpressCheckoutRequestType
populateRequestObject(request)
'Invoke the API
Dim wrapper As New SetExpressCheckoutReq
wrapper.SetExpressCheckoutRequest = request
Dim service As New PayPalAPIInterfaceServiceService
Dim setECResponse As SetExpressCheckoutResponseType = service.SetExpressCheckout(wrapper)
'Check for API return status
Dim CurrContext As HttpContext = HttpContext.Current
CurrContext.Items.Add("paymentDetails", request.SetExpressCheckoutRequestDetails.PaymentDetails)
setKeyResponseObjects(service, setECResponse)
Else
End If
End Sub
Private Sub SetShippingAddress(ByRef shippingAddress As AddressType)
Dim selectedCountry As New Country
Dim currentUser As User = Session("currentUser")
selectedCountry.GetCountryDetails(currentPreSale.DeliveryCountryId.ToString())
shippingAddress.Name = currentUser.FirstName & " " & currentUser.LastName
shippingAddress.Street1 = currentPreSale.DeliveryAddress
shippingAddress.Street2 = ""
shippingAddress.CityName = ""
shippingAddress.StateOrProvince = ""
shippingAddress.Country = [Enum].Parse(GetType(CountryCodeType), selectedCountry.CountryCode)
shippingAddress.Phone = currentUser.Phone & ""
shippingAddress.PostalCode = ""
End Sub
Private Sub populateRequestObject(ByRef request As SetExpressCheckoutRequestType)
Dim deliveryAddress As New Address
Dim currentUser As User = Session("currentUser")
Dim selectedCurrency As New Currency
selectedCurrency.GetCurrencyDetails(currentPreSale.CurrencyId.ToString())
'Dim userDetails As New UserDetails
Dim currency As CurrencyCodeType = selectedCurrency.PayPalCurrencyCode
Dim ecDetails As New SetExpressCheckoutRequestDetailsType
Dim paymentDetails As New PaymentDetailsType
Dim orderTotal As Double = 0
Dim itemTotal As Double = 0
Dim shippingValue As Double = currentPreSale.ShippingTotal
Dim HandlingTotal As Double = 0
Dim TaxTotal As Double = 0
Dim shipAddress As New AddressType
Dim dataTableCarrinho As DataTable
Dim dataRowCarrinho As DataRow
If currentPreSale.ShippingTotal > 0 Then
SetShippingAddress(shipAddress)
End If
'userDetails.Get_ItemDetails(Session("userId").ToString())
ecDetails.ReturnURL = ConfigurationManager.AppSettings("appURL") & "doExpressCheckoutPayment.aspx"
ecDetails.CancelURL = ConfigurationManager.AppSettings("appCurrentServer") & Page.GetRouteUrl("paypalCancel" & UCase(Left(Session("language"), 2)), New With {.lang = Left(Session("language"), 2)})
ecDetails.BuyerEmail = currentUser.Email
ecDetails.ReqConfirmShipping = 0
ecDetails.AddressOverride = 0
If CDec(currentPreSale.ShippingTotal) > 0 Then
ecDetails.NoShipping = 0
Else
ecDetails.NoShipping = 1
End If
'Payment Details
If (shippingValue > 0) Then
paymentDetails.ShippingTotal = New BasicAmountType(currency, currentPreSale.ShippingTotal)
End If
paymentDetails.OrderDescription = "KTB Order"
paymentDetails.PaymentAction = PaymentActionCodeType.SALE
orderTotal += shippingValue
'Lista de Items - GUY preencher
dataTableCarrinho = Session("ShoppingCartDT")
For Each dataRowCarrinho In dataTableCarrinho.Rows
Dim currentProduct As New Product
currentProduct.GetProductDetails(dataRowCarrinho("ProductId").ToString(), Session("LanguageId").ToString())
Dim itemDetails As New PaymentDetailsItemType
itemDetails.Name = currentProduct.Title
'itemDetails.Amount = New BasicAmountType(currency, dataRowCarrinho("Price").ToString())
itemDetails.Amount = New BasicAmountType(currency, CDec(dataRowCarrinho("Price")))
itemDetails.Quantity = CInt(dataRowCarrinho("Quantity"))
itemDetails.Tax = New BasicAmountType(currency, 0)
itemDetails.Description = ""
itemDetails.ItemCategory = ItemCategoryType.PHYSICAL
paymentDetails.PaymentDetailsItem.Add(itemDetails)
orderTotal += CDec(dataRowCarrinho("Price")) * CInt(dataRowCarrinho("Quantity"))
itemTotal += CDec(dataRowCarrinho("Price")) * CInt(dataRowCarrinho("Quantity"))
Next
'ExceptionUtility.LogInfo("orderTotal = " & orderTotal)
'ExceptionUtility.LogInfo("itemTotal = " & itemTotal)
'ExceptionUtility.LogInfo("shippingTotal = " & (currentPreSale.ShippingTotal * currentPreSale.ExchangeRate))
'paymentDetails.ItemTotal = New BasicAmountType(currency, CDec(currentPreSale.ProductTotal * currentPreSale.ExchangeRate))
'paymentDetails.OrderTotal = New BasicAmountType(currency, CDec((currentPreSale.ProductTotal + currentPreSale.ShippingTotal) * currentPreSale.ExchangeRate))
paymentDetails.ItemTotal = New BasicAmountType(currency, itemTotal)
paymentDetails.OrderTotal = New BasicAmountType(currency, orderTotal)
ecDetails.PaymentDetails.Add(paymentDetails)
ecDetails.PaymentDetails(0).ShipToAddress = shipAddress
request.SetExpressCheckoutRequestDetails = ecDetails
End Sub
Private Sub setKeyResponseObjects(ByVal service As PayPalAPIInterfaceServiceService, ByVal setECResponse As SetExpressCheckoutResponseType)
Dim keyResponseParameters As New Dictionary(Of String, String)
keyResponseParameters.Add("API Status", setECResponse.Ack.ToString())
Dim CurrContext As HttpContext = HttpContext.Current
If (setECResponse.Ack.Equals(AckCodeType.FAILURE) Or ((Not IsNothing(setECResponse.Errors)) And setECResponse.Errors.Count > 0)) Then
ExceptionUtility.LogInfo(setECResponse.Errors.Item(0).LongMessage)
CurrContext.Items.Add("Response_error", setECResponse.Errors)
CurrContext.Items.Add("Response_redirectURL", Nothing)
Else
CurrContext.Items.Add("Response_error", Nothing)
keyResponseParameters.Add("EC token", setECResponse.Token)
Dim paypalUrl As String = ConfigManager.Instance.GetProperty("paypalUrl").ToString()
CurrContext.Items.Add("Response_redirectURL", paypalUrl + "_express-checkout&token=" + setECResponse.Token)
End If
CurrContext.Items.Add("Response_keyResponseObject", keyResponseParameters)
CurrContext.Items.Add("Response_apiName", "SetExpressCheckout")
CurrContext.Items.Add("Response_requestPayload", service.getLastRequest())
CurrContext.Items.Add("Response_responsePayload", service.getLastResponse())
Response.Redirect(CurrContext.Items.Item("Response_redirectURL"))
'Server.Transfer("APIResponse.aspx")
Dim a As String = ""
End Sub
End Class
Non Working version
Imports PayPal.PayPalAPIInterfaceService.Model
Imports PayPal.PayPalAPIInterfaceService
Imports PayPal.Manager
Partial Class paypalExpressCheckout
Inherits System.Web.UI.Page
Dim currentPreSale As New PreSale
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Session("ShoppingCartDT") Is Nothing Then
currentPreSale = Session("currentPreSale")
Dim request As New SetExpressCheckoutRequestType
populateRequestObject(request)
'Invoke the API
Dim wrapper As New SetExpressCheckoutReq
wrapper.SetExpressCheckoutRequest = request
Dim service As New PayPalAPIInterfaceServiceService
Dim setECResponse As SetExpressCheckoutResponseType = service.SetExpressCheckout(wrapper)
'Check for API return status
Dim CurrContext As HttpContext = HttpContext.Current
CurrContext.Items.Add("paymentDetails", request.SetExpressCheckoutRequestDetails.PaymentDetails)
setKeyResponseObjects(service, setECResponse)
Else
End If
End Sub
Private Sub SetShippingAddress(ByRef shippingAddress As AddressType)
Dim selectedCountry As New Country
Dim currentUser As User = Session("currentUser")
selectedCountry.GetCountryDetails(currentPreSale.DeliveryCountryId.ToString())
shippingAddress.Name = currentUser.FirstName & " " & currentUser.LastName
shippingAddress.Street1 = currentPreSale.DeliveryAddress
shippingAddress.Street2 = ""
shippingAddress.CityName = ""
shippingAddress.StateOrProvince = ""
shippingAddress.Country = [Enum].Parse(GetType(CountryCodeType), selectedCountry.CountryCode)
shippingAddress.Phone = currentUser.Phone & ""
shippingAddress.PostalCode = ""
End Sub
Private Sub populateRequestObject(ByRef request As SetExpressCheckoutRequestType)
Dim deliveryAddress As New Address
Dim currentUser As User = Session("currentUser")
Dim selectedCurrency As New Currency
selectedCurrency.GetCurrencyDetails(currentPreSale.CurrencyId.ToString())
'Dim userDetails As New UserDetails
Dim currency As CurrencyCodeType = selectedCurrency.PayPalCurrencyCode
Dim ecDetails As New SetExpressCheckoutRequestDetailsType
Dim paymentDetails As New PaymentDetailsType
Dim orderTotal As Double = 0
Dim itemTotal As Double = 0
Dim shippingValue As Double = currentPreSale.ShippingTotal
Dim HandlingTotal As Double = 0
Dim TaxTotal As Double = 0
Dim shipAddress As New AddressType
Dim dataTableCarrinho As DataTable
Dim dataRowCarrinho As DataRow
If currentPreSale.ShippingTotal > 0 Then
SetShippingAddress(shipAddress)
End If
'userDetails.Get_ItemDetails(Session("userId").ToString())
ecDetails.ReturnURL = ConfigurationManager.AppSettings("appURL") & "doExpressCheckoutPayment.aspx"
ecDetails.CancelURL = ConfigurationManager.AppSettings("appCurrentServer") & Page.GetRouteUrl("paypalCancel" & UCase(Left(Session("language"), 2)), New With {.lang = Left(Session("language"), 2)})
ecDetails.BuyerEmail = currentUser.Email
ecDetails.ReqConfirmShipping = 0
ecDetails.AddressOverride = 0
If CDec(currentPreSale.ShippingTotal) > 0 Then
ecDetails.NoShipping = 0
Else
ecDetails.NoShipping = 1
End If
'Payment Details
If (shippingValue > 0) Then
paymentDetails.ShippingTotal = New BasicAmountType(currency, currentPreSale.ShippingTotal * currentPreSale.ExchangeRate)
End If
paymentDetails.OrderDescription = "KTB Order"
paymentDetails.PaymentAction = PaymentActionCodeType.SALE
orderTotal += shippingValue * currentPreSale.ExchangeRate
'Lista de Items - GUY preencher
dataTableCarrinho = Session("ShoppingCartDT")
For Each dataRowCarrinho In dataTableCarrinho.Rows
Dim currentProduct As New Product
currentProduct.GetProductDetails(dataRowCarrinho("ProductId").ToString(), Session("LanguageId").ToString())
Dim itemDetails As New PaymentDetailsItemType
itemDetails.Name = currentProduct.Title
'itemDetails.Amount = New BasicAmountType(currency, dataRowCarrinho("Price").ToString())
itemDetails.Amount = New BasicAmountType(currency, CDec(dataRowCarrinho("Price") * currentPreSale.ExchangeRate))
itemDetails.Quantity = CInt(dataRowCarrinho("Quantity"))
itemDetails.Tax = New BasicAmountType(currency, 0)
itemDetails.Description = ""
itemDetails.ItemCategory = ItemCategoryType.PHYSICAL
paymentDetails.PaymentDetailsItem.Add(itemDetails)
orderTotal += CDec(dataRowCarrinho("Price")) * CInt(dataRowCarrinho("Quantity") * currentPreSale.ExchangeRate)
itemTotal += CDec(dataRowCarrinho("Price")) * CInt(dataRowCarrinho("Quantity") * currentPreSale.ExchangeRate)
Next
'ExceptionUtility.LogInfo("orderTotal = " & orderTotal)
'ExceptionUtility.LogInfo("itemTotal = " & itemTotal)
'ExceptionUtility.LogInfo("shippingTotal = " & (currentPreSale.ShippingTotal * currentPreSale.ExchangeRate))
'paymentDetails.ItemTotal = New BasicAmountType(currency, CDec(currentPreSale.ProductTotal * currentPreSale.ExchangeRate))
'paymentDetails.OrderTotal = New BasicAmountType(currency, CDec((currentPreSale.ProductTotal + currentPreSale.ShippingTotal) * currentPreSale.ExchangeRate))
paymentDetails.ItemTotal = New BasicAmountType(currency, itemTotal)
paymentDetails.OrderTotal = New BasicAmountType(currency, orderTotal)
ecDetails.PaymentDetails.Add(paymentDetails)
ecDetails.PaymentDetails(0).ShipToAddress = shipAddress
request.SetExpressCheckoutRequestDetails = ecDetails
End Sub
Private Sub setKeyResponseObjects(ByVal service As PayPalAPIInterfaceServiceService, ByVal setECResponse As SetExpressCheckoutResponseType)
Dim keyResponseParameters As New Dictionary(Of String, String)
keyResponseParameters.Add("API Status", setECResponse.Ack.ToString())
Dim CurrContext As HttpContext = HttpContext.Current
If (setECResponse.Ack.Equals(AckCodeType.FAILURE) Or ((Not IsNothing(setECResponse.Errors)) And setECResponse.Errors.Count > 0)) Then
ExceptionUtility.LogInfo(setECResponse.Errors.Item(0).LongMessage)
CurrContext.Items.Add("Response_error", setECResponse.Errors)
CurrContext.Items.Add("Response_redirectURL", Nothing)
Else
CurrContext.Items.Add("Response_error", Nothing)
keyResponseParameters.Add("EC token", setECResponse.Token)
Dim paypalUrl As String = ConfigManager.Instance.GetProperty("paypalUrl").ToString()
CurrContext.Items.Add("Response_redirectURL", paypalUrl + "_express-checkout&token=" + setECResponse.Token)
End If
CurrContext.Items.Add("Response_keyResponseObject", keyResponseParameters)
CurrContext.Items.Add("Response_apiName", "SetExpressCheckout")
CurrContext.Items.Add("Response_requestPayload", service.getLastRequest())
CurrContext.Items.Add("Response_responsePayload", service.getLastResponse())
Response.Redirect(CurrContext.Items.Item("Response_redirectURL"))
'Server.Transfer("APIResponse.aspx")
Dim a As String = ""
End Sub
End Class
it keeps throwing me the following error:
Item amount is invalid.
Anyone got any clue on what is happeing and how to solve it?
Thx

Related

Why crystal report prompting me for parameter field value while I have written code for it

Why crystal report prompting me for parameter field value while I have written code for it.
Private void ReportVeiwer_Load(object sender, EventArgs e)
{
ReportDocument reportdoc = new ReportDocument();
///string invoice_number = (;
Invoice invoicerpt = new Invoice();
ParameterField paramfield = new ParameterField();
ParameterFields paramfields = new ParameterFields();
paramfield.Name = "Invoice_Number";
ParameterDiscreteValue dicval = new ParameterDiscreteValue();
dicval.Value = User_Info.invoice_number;
paramfield.CurrentValues.Add(dicval);
paramfields.Add(paramfield);
ReportVeiwer rptveiwer = new ReportVeiwer();
rptveiwer.crystalReportViewer1.ParameterFieldInfo = paramfields;
reportdoc.Load(#"D:\Furqan\SchoolManagementSystem\SchoolManagementSystem\Invoice.rpt");
crystalReportViewer1.ReportSource = reportdoc;
reportdoc.SetDatabaseLogon("PC-Name/User", "Password", ".", "Database");
}
Load the report first. Then, set the parameter value...

Convert all Solidworks files in folder to step files macro

I was searching around and looking for a macro that will when run it will convert the files in the location into .stp files and I came across the below. how can i manipulate it to grab the next file in the folder and continue the next files and convert them until all the files have been converted.
Dim swApp As Object
Dim Part As Object
Dim FilePath As String
Dim sFilePath As String
Dim PathSize As Long
Dim PathNoExtention As String
Dim NewFilePath As String
Dim FileLocation As String
Dim sPath As String
Dim i As Long
Dim bRebuild As Boolean
Dim bRet As Boolean
Dim sRev As String
Dim nErrors As Long
Dim nWarnings As Long
Sub main()
Set swApp = Application.SldWorks
Set Part = swApp.ActiveDoc
FilePath = Part.GetPathName
PathSize = Strings.Len(FilePath)
sPath = Left(Part.GetPathName, InStrRev(Part.GetPathName, "\"))
sRev = Part.CustomInfo("re") 'Change Configuration Property name here
FileLocation = "C:"
PathNoExtension = Strings.Left(FilePath, PathSize - 7)
Part.SaveAs (PathNoExtension & "rev" & sRev & ".step")
End Sub
You could do this a few different ways if you're not using a VB6 Macro. If you use a .NET Macro (Visual Basic or C#), they support .NET libraries which makes this process quite simple. I've created the following Console Application in C#. You could create the same thing as a .NET Macro in SolidWorks. The important thing to add to the example you provided is the foreach statement which will iterate over all of the files in the directory and only perform the translation on SolidWorks Parts or Assemblies.
using SolidWorks.Interop.sldworks;
using System;
using System.IO;
namespace CreateStepFiles
{
class Program
{
static SldWorks swApp;
static void Main(string[] args)
{
string directoryName = GetDirectoryName();
if (!GetSolidWorks())
{
return;
}
int i = 0;
foreach (string fileName in Directory.GetFiles(directoryName))
{
if (Path.GetExtension(fileName).ToLower() == ".sldprt")
{
CreateStepFile(fileName, 1);
i += 1;
}
else if (Path.GetExtension(fileName).ToLower() == ".sldasm")
{
CreateStepFile(fileName, 2);
i += 1;
}
}
Console.WriteLine("Finished converting {0} files", i);
}
static void CreateStepFile(string fileName, int docType)
{
int errors = 0;
int warnings = 0;
ModelDoc2 swModel = swApp.OpenDoc6(fileName, docType, 1, "", ref errors, ref warnings);
string stepFile = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName), ".STEP");
swModel.Extension.SaveAs(stepFile, 0, 1, null, ref errors, ref warnings);
Console.WriteLine("Created STEP file: " + stepFile);;
swApp.CloseDoc(fileName);
}
static string GetDirectoryName()
{
Console.WriteLine("Directory to Converty");
string s = Console.ReadLine();
if (Directory.Exists(s))
{
return s;
}
Console.WriteLine("Directory does not exists, try again");
return GetDirectoryName();
}
static bool GetSolidWorks()
{
try
{
swApp = (SldWorks)Activator.CreateInstance(Type.GetTypeFromProgID("SldWorks.Application"));
if (swApp == null)
{
throw new NullReferenceException(nameof(swApp));
}
if (!swApp.Visible)
{
swApp.Visible = true;
}
Console.WriteLine("SolidWorks Loaded");
return true;
}
catch (Exception)
{
Console.WriteLine("Could not launch SolidWorks");
return false;
}
}
}
}

Get list of installed software in eclipse through program

Using Platform.getBundleGroupProviders() and org.eclipse.core.runtime.IBundleGroup I am able to retrieve the list of installed features in Eclipse, but, is there an API through which I can get the list of installed software?
Thanks for your help!
Here is the final code that returns the complete list of installed software:
private static final String FEATURE_NAME = "df_LT.featureName";
private static List<String> installedSoftwareList(String toMatch) {
ProvisioningUI provisioningUI = ProvisioningUI.getDefaultUI();
String profileId = provisioningUI.getProfileId();
ProvisioningSession provisioningSession = provisioningUI.getSession();
IProfileRegistry profileReg = (IProfileRegistry)provisioningSession.getProvisioningAgent().getService(IProfileRegistry.SERVICE_NAME);
IQueryable<IInstallableUnit> queryable = profileReg.getProfile(profileId);
IQuery<IInstallableUnit> query = QueryUtil.createIUPropertyQuery(QueryUtil.PROP_TYPE_GROUP, "true");
IQueryResult<IInstallableUnit> iqr = queryable.query(query, new NullProgressMonitor());
List<String> softwareList = null;
for(IInstallableUnit iu : iqr.toSet()){
if(softwareList == null){
softwareList = new ArrayList<String>();
}
String id = iu.getId();
String propName = iu.getProperty(IInstallableUnit.PROP_NAME);
String featureName = iu.getProperty(FEATURE_NAME);
if (id.startsWith(toMatch)) {
softwareList.add(propName.equals("%featureName") ? featureName : propName);
//System.out.println( "ID: " + id + " | Name: " + (propName.equals("%featureName") ? featureName : propName));
}
}
return softwareList;
}
For example, to get all installed software with id = org.eclipse.* , you can call:
installedSoftwareList("org.eclipse");
This code lists all the installable units in the current profile:
ProvisioningUI provisioningUI = ProvisioningUI.getDefaultUI();
String profileId = provisioningUI.getProfileId();
ProvisioningSession provisioningSession = provisioningUI.getSession();
IProfileRegistry profileReg = (IProfileRegistry)provisioningSession.getProvisioningAgent().getService(IProfileRegistry.SERVICE_NAME);
IQueryable<IInstallableUnit> queryable = profileReg.getProfile(profileId);
IQuery<IInstallableUnit> query = QueryUtil.createIUAnyQuery();
IQueryResult<IInstallableUnit> result = queryable.query(query, new NullProgressMonitor());
for (final IInstallableUnit iu : result)
{
System.out.println(iu);
}
I have left out lots of null checks and exception catching.
You can use QueryUtil to create various other queries such as IUs which are groups.

How to send successfully push notification of APNS in production

How to send successfully push notification of APNS in production
When I use in development, it's work.
But use in production,it appear error.
My app is in App Store, so p12 file is production.
My server side is asp.net.
asp.net code:
//key
//True if you are using sandbox certificate, or false if using production
bool sandbox = false;
string p12File = "InspirePass.p12";
string p12Filename = System.IO.Path.Combine(MapPath("~"), p12File);
string p12FilePassword = "xxxxxxxx";
NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);
//send
foreach (DataRow eachUserRow in userTable.Rows)
{
//Create a new notification to send
if (eachUserRow["pushStatus"].ToString() == "N")
{ //////no repeat
Notification alertNotification = new Notification(eachUserRow["device_token"].ToString());
alertNotification.Payload.Alert.Body = eachUserRow["menuMessage"].ToString() + "(" + eachUserRow["menuTitle"].ToString() + ")";
alertNotification.Payload.Sound = "default";
alertNotification.Payload.Badge = selectEventPush_IOS.Rows.Count + selectSignPush_IOS.Rows.Count;
// alertNotification.Payload. = 1;
string[] items = new string[1];
string[] items2 = new string[1];
if (userTable.Rows.Count > 0)
{
items[0] = Convert.ToString(selectEventPush_IOS.Rows.Count);
items2[0] = Convert.ToString(selectSignPush_IOS.Rows.Count);
}
alertNotification.Payload.CustomItems.Add("items2", items2);
alertNotification.Payload.CustomItems.Add("items", items);
//Queue the notification to be sent
if (service.QueueNotification(alertNotification))
result = 1;
else
result = -1;
///////change chat_document/pushStatus=Y
string Identifier = "";
Identifier = eachUserRow["Identifier"].ToString();
DataRow yespushuser = DBiphone.UpdatedPushStatus(Identifier);
}
}//end if
service.Close();
service.Dispose();
Response.Write(result.ToString());

saving email attachments as binary to the database using c#

I can get email attachments from exchange server 2003 (MAPI.Attachment). How can I save the pdf attachment file as binary into the database?
Here's some code to understand better. For testing purposes I am saving the attachment pdf file into a filesystem. How ca I go about saving that into a database? Or how can I convert that into a byte array? Also, how can I get the size of the file since I need that when I declare the byte array "fileData"...
byte[] fileData = new byte[10000];
string[] fileTokens = new string[2];
string[] result = new string[3];
message.Unread = false;
emailSubject = message.Subject.ToString();
emailBody = message.Text.ToString();
MAPI.Attachments test = null;
test = (MAPI.Attachments)message.Attachments;
int attachmentCount = (int)test.Count;
for (int loopCounter = 1; loopCounter <= attachmentCount; loopCounter++)
{
MAPI.Attachment test2 = (MAPI.Attachment)test.get_Item(loopCounter);
bool temp = (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0);
if (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0)
{
//test2.ReadFromFile(fileData);
test2.WriteToFile("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
}
RequestHistorySet historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);
bool res = historySet.Update();
message.Unread = false;
message.Update();
And here's the Update function from historySet Class
public bool Update()
{
using (SqlConnection mySqlConnection = ...))
{
// Set up the Command object
SqlCommand myCommand = new SqlCommand("CONNECTION STRING..", mySqlConnection);
// Set up the OriginalName parameter
SqlParameter prmId = new SqlParameter("#id", SqlDbType.Int);
prmId.Value = id;
myCommand.Parameters.Add(prmId);
SqlParameter prmRequsetDate = new SqlParameter("#requestDate", SqlDbType.DateTime);
prmRequsetDate.Value = requestDate;
myCommand.Parameters.Add(prmRequsetDate);
// Set up the FileData parameter
SqlParameter prmFileData = new SqlParameter("#uplodedQuote_File ", SqlDbType.VarBinary);
prmFileData.Value = fileData;
prmFileData.Size = fileData.Length;
myCommand.Parameters.Add(prmFileData);
SqlParameter prmFileExtension = new SqlParameter("#uplodedQuote_Ext", SqlDbType.NVarChar);
prmFileExtension.Value = fileExtension;
myCommand.Parameters.Add(prmFileExtension);
// Execute the command, and clean up.
mySqlConnection.Open();
bool result = myCommand.ExecuteNonQuery() > 0;
mySqlConnection.Close();
return result;
}
}
As of now this is what I have done. I save it to a filesystem and then read from there.
test2.WriteToFile("d:\\data\\" + test2.Name);
fileData = FileToByteArray("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
TryToDelete("d:\\data\\" + test2.Name);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);