I have this scenario:
Server is in (GMT +3) time zone
Client is in (GMT -5) time zone
Server returns a DateTime to the client, let's say it is "10JAN2013 00:00" and AFAIK the DateTime has no time zone info attached to it. The time in the client side is converted into the client's time zone which is "09JAN2013 16:00"! the DTK is specified to DTK.Unspecified.
My question, how did the client know the time zone of the server if the DateTime has no timezone information? this is confusing to me! Is it sent in the header of SOAP or something like that?
They may or may not know. When DateTime objects are passed between client and server, they're serialized into some common format understood by the two parties. In some of those formats, such as XML, the time zone information is sent across the wire: if you have a DateTime with DateTimeKind.Utc, a 'Z' will be appended to the serialized date; for Local the timezone will be added, and for Unspecified nothing will be added, so the other party knows which format to use. In other formats, such as JSON, the server will not send anything in the date time if the kind is Utc, but will add the local time zone information for the other kinds (there's no distinction in the JSON format for Local and Unspecified; IIRC the receiving party will treat such information as Local).
If you want to see what goes on the wire, you can run the program below, while having a network capture tool such as Fiddler, to see what the client is sending to the server.
public class StackOverflow_14132566
{
[ServiceContract]
public interface ITest
{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
DateTime Add10Hours(DateTime input, string description);
}
public class Service : ITest
{
public DateTime Add10Hours(DateTime input, string description)
{
return input.AddHours(10);
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "basic");
host.AddServiceEndpoint(typeof(ITest), new WebHttpBinding(), "web").Behaviors.Add(new WebHttpBehavior());
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress + "/basic"));
ITest proxy = factory.CreateChannel();
Console.WriteLine(proxy.Add10Hours(new DateTime(2013, 1, 2, 19, 29, 0, DateTimeKind.Utc), "XML, UTC"));
Console.WriteLine(proxy.Add10Hours(new DateTime(2013, 1, 2, 19, 29, 0, DateTimeKind.Local), "XML, Local"));
Console.WriteLine(proxy.Add10Hours(new DateTime(2013, 1, 2, 19, 29, 0, DateTimeKind.Unspecified), "XML, Unspecified"));
((IClientChannel)proxy).Close();
factory.Close();
factory = new ChannelFactory<ITest>(new WebHttpBinding(), new EndpointAddress(baseAddress + "/web"));
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
proxy = factory.CreateChannel();
Console.WriteLine(proxy.Add10Hours(new DateTime(2013, 1, 2, 19, 29, 0, DateTimeKind.Utc), "JSON, UTC"));
Console.WriteLine(proxy.Add10Hours(new DateTime(2013, 1, 2, 19, 29, 0, DateTimeKind.Local), "JSON, Local"));
Console.WriteLine(proxy.Add10Hours(new DateTime(2013, 1, 2, 19, 29, 0, DateTimeKind.Unspecified), "JSON, Unspecified"));
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
Related
Protected Overrides Function getJsonPrivate(method As String, otherParameters() As Tuple(Of String, String)) As String
Dim base = "https://www.coinmex.com"
Dim premethod = "/api/v1/spot/ccex/"
Dim longmethod = premethod + method
Dim timestampstring = getEstimatedTimeStamp().ToString
Dim stringtosign = timestampstring + "GET" + longmethod + "{}" '1553784499976GET/api/v1/spot/ccex/account/assets{}
Dim hasher = New System.Security.Cryptography.HMACSHA256(System.Text.Encoding.UTF8.GetBytes(_secret1))
Dim sighashbyte = hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringtosign))
Dim signature = System.Convert.ToBase64String(sighashbyte) '"FIgrJFDOQctqnkOTyuv6+uTy6xw3OZiP4waC1u6P5LU="=
Dim url = base + longmethod 'https://www.coinmex.com/api/v1/spot/ccex/account/assets
'_apiKey1="cmx-1027e54e4723b09810576f8e7a5413**"
'_passphrase1= 1Us6&f%*K#Qsqr**
'
Dim response = CookieAwareWebClient.downloadString1(url, "", {Tuple.Create("ACCESS-KEY", _apiKey1), Tuple.Create("ACCESS-SIGN", signature), Tuple.Create("ACCESS-TIMESTAMP", timestampstring), Tuple.Create("ACCESS-PASSPHRASE", _passphrase1)})
Return response
End Function
Public Overrides Sub readbalances()
typicalReadBalances("account/assets", "data", "currencyCode", "available", "frozen", "", {})
End Sub
I think I did it like what's listed here
https://github.com/coinmex/coinmex-official-api-docs/blob/master/README_EN.md#1-access-account-information
# Request
GET /api/v1/spot/ccex/account/assets
# Response
[
{
"available":"0.1",
"balance":"0.1",
"currencyCode":"ETH",
"frozen":"0",
"id":1
},
{
"available":"1",
"balance":"1",
"currencyCode":"USDT",
"frozen":"0",
"id":1
}
]
And for Signature
This is the manual says
The ACCESS-SIGN header is the output generated by using HMAC SHA256 to
create the HMAC SHA256 using the BASE64 decoding secret key in the
prehash string to generate timestamp + method + requestPath + "?" +
queryString + body (where ‘+’ represents the string concatenation) and
BASE64 encoded output. The timestamp value is the same as the
ACCESS-TIMESTAMP header. This body is the request body string or
omitted if there is no request body (usually the GET request). This
method should be capitalized.
Remember that before using it as the key to HMAC, base64 decoding (the
result is 64 bytes) is first performed on the 64-bit alphanumeric
password string. In addition, the digest output is base64 encoded
before sending the header.
User submitted parameters must be signed except for sign. First, the
string to be signed is ordered according to the parameter name (first
compare the first letter of all parameter names, in alphabetic order,
if you encounter the same first letter, then you move to the second
letter, and so on).
For example, if we sign the following parameters
curl "https://www.coinmex.com/api/v1/spot/ccex/orders?limit=100"
Timestamp = 1590000000.281
Method = "POST"
requestPath = "/api/v1/spot/ccex/orders"
queryString= "?limit=100"
body = {
'code': 'ct_usdt',
'side': 'buy',
'type': 'limit',
'size': '1',
'price': '1',
'funds': '',
}
Generate the string to be signed
Message = '1590000000.281GET/api/v1/spot/ccex/orders?limit=100{"code": "ct_usdt", "side": "buy", "type": "limit", "size": "1", "price": "0.1", "funds": ""}'
Then, the character to be signed is added with the private key
parameters to generate the final character string to be signed.
For example:
hmac = hmac(secretkey, Message, SHA256)
Signature = base64.encode(hmac.digest())
I thought may be the _secret1 is a base64 string rather than utf8 so I changed to
Dim base = "https://www.coinmex.com"
Dim premethod = "/api/v1/spot/ccex/"
Dim longmethod = premethod + method
Dim timestampstring = getEstimatedTimeStamp().ToString
'Dim stringtosign = timestampstring + "GET" + longmethod + "{}" '1553784499976GET/api/v1/spot/ccex/account/assets{} also doesn't work
Dim stringtosign = timestampstring + "GET" + longmethod '1553784499976GET/api/v1/spot/ccex/account/assets
Dim hasher = New System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(_secret1)) 'secret looks like 43a90185f5b7ab25af045e9e64bac5dc745934f359f1806fcdd2a4af80ac2
Dim sighashbyte = hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringtosign))
Dim signature = Convert.ToBase64String(sighashbyte) '"FIgrJFDOQctqnkOTyuv6+uTy6xw3OZiP4waC1u6P5LU="=
Dim url = base + longmethod 'https://www.coinmex.com/api/v1/spot/ccex/account/assets
'_apiKey1="cmx-1027e54e4723b09810576f8e7a5413**"
'_passphrase1= 1Us6&f%*K#Qsq***
'
Dim response = CookieAwareWebClient.downloadString1(url, "", {Tuple.Create("ACCESS-KEY", _apiKey1), Tuple.Create("ACCESS-SIGN", signature), Tuple.Create("ACCESS-TIMESTAMP", timestampstring), Tuple.Create("ACCESS-PASSPHRASE", _passphrase1)})
Return response
Not working either.
The secret key (I truncated a few letters) look like
43a90185f5b7ab25af045e9e64bac5dc745934f359f1806fcdd2a4af80ac2
Is this something that should be decoded as base 64 or utf8 or what?
The spec says it's 64. However, it doesn't look like a 64 encoded string. It looks like the letters are from 0-f
Best answers will:
1. Tell me what went wrong in the code. I made the change. Try. Run. Works. Awesome.
A good answer will
2. A sample simulation with a fake/real signatures/nonce/passphrase and real actual headers and signatures. So I can see where exactly I have a wrong result.
Update: I modified the code again. I change the timestamp to seconds instead of milisecons. I remove the {}. I use both way.
Dim base = "https://www.coinmex.com"
Dim premethod = "/api/v1/spot/ccex/"
Dim longmethod = premethod + method
Dim timestampstring = (getEstimatedTimeStamp() / 1000).ToString
Dim stringtosign = timestampstring + "GET" + longmethod '1555154812.857GET/api/v1/spot/ccex/account/assets
Dim hasher = New System.Security.Cryptography.HMACSHA256(System.Text.Encoding.UTF8.GetBytes(_secret1)) '"43a90185f5b7ab25af045e9e64bac5dc745934f359f1806fcdd2a4af80ac2******
Dim sighashbyte = hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringtosign))
Dim signature = Convert.ToBase64String(sighashbyte) '"FIgrJFDOQctqnkOTyuv6+uTy6xw3OZiP4waC1u6P5LU="=
Dim url = base + longmethod 'https://www.coinmex.com/api/v1/spot/ccex/account/assets
'_apiKey1="cmx-1027e54e4723b09810576f8e7a5413**"
'_passphrase1= 1Us6&f%*K#QsqrYZ
'
Dim response = CookieAwareWebClient.downloadString1(url, "", {Tuple.Create("ACCESS-KEY", _apiKey1), Tuple.Create("ACCESS-SIGN", signature), Tuple.Create("ACCESS-TIMESTAMP", timestampstring), Tuple.Create("ACCESS-PASSPHRASE", _passphrase1)})
Return response
Still doesn't work.
Current Error is
Message = "The remote server returned an error: (401) Unauthorized."
I would love to give some read-only API key. Hang on. Or create an empty account and then have a read only API key
The documentation states
This body is the request body string or omitted if there is no request body (usually the GET request)
Note: emphasis mine
yet you include an empty JSON object on a GET request
Dim stringtosign = timestampstring + "GET" + longmethod + "{}" '1553784499976GET/api/v1/spot/ccex/account/assets{}
That {} should not be included in a GET request.
'1553784499976GET/api/v1/spot/ccex/account/assets
Dim stringtosign = timestampstring + "GET" + longmethod
So it appears you were not constructing the signature correctly as per documentation.
Noticed that the docs
The root URL for REST access:https://www.coinmex.pro
while you are trying to call "https://www.coinmex.com"
Timestamp
Unless otherwise specified, all timestamps in APIs are returned in microseconds.
The ACCESS-TIMESTAMP header must be the number of seconds since UTC's
time Unix Epoch. Decimal values are allowed. Your timestamp must be
within 30 seconds of the API service time, otherwise your request will
be considered expired and rejected. If you think there is a large time
difference between your server and the API server, then we recommend
that you use the time point to check the API server time.
note: emphasis mine
Following extension method was used to calculate time stamp
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Converts the value of the current <see cref="System.DateTime"/> object to Unix Time.
/// </summary>
/// <param name="dateTime"></param>
/// <remarks>
/// </remarks>
/// This method first converts the current instance to UTC before returning its Unix time.
/// <returns>
/// A <see cref="System.Int64"/> defined as the number of seconds that have elapsed since midnight Coordinated Universal Time (UTC), January 1, 1970, not counting leap seconds.
/// </returns>
public static long ToUnixTimeSeconds(this DateTime dateTime) {
if (dateTime.ToUniversalTime() < Epoch) {
return 0;
}
var totalSeconds = dateTime.ToUniversalTime().Subtract(Epoch).TotalSeconds;
var timestamp = Convert.ToInt64(totalSeconds);
return timestamp;
}
I did the following Test to see if I could call the API following the documentation and it appears to have worked.
I used c# however
[TestClass]
public class CoinMaxAPITests {
const string apiKey1 = "cmx-1027e54e4723b09810576f8e7a5413**";
const string fakeSecret = "43a90185f5b7ab25af045e9e64bac5dc745934f359f1806fcdd2a4af80ac23==";
const string passphrase1 = "1Us6&f%*K#QsqrYZ";
Lazy<HttpClient> http = new Lazy<HttpClient>(() => {
var rootUrl = "https://www.coinmex.pro";
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler {
CookieContainer = cookies,
UseCookies = true,
};
var client = new HttpClient() {
BaseAddress = new Uri(rootUrl)
};
client.DefaultRequestHeaders.TryAddWithoutValidation("ACCESS-KEY", apiKey1);
client.DefaultRequestHeaders.TryAddWithoutValidation("ACCESS-PASSPHRASE", passphrase1);
return client;
});
[TestMethod]
public async Task Should_Accept_Signature() {
//Arrange
var requestPath = "/api/v1/spot/public/time";
var method = "GET";
var timeStamp = getEstimatedTimeStamp().ToString(); //"1555253371"
var message = timeStamp + method + requestPath; //"1555253371GET/api/v1/spot/public/time"
var secretKey = Convert.FromBase64String(fakeSecret);
var hmac = new HMACSHA256(secretKey);
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
var signature = Convert.ToBase64String(hash);//Jzui/eO3iyLTD6L9qVkUO0EBpZP/lFhx1HlsbuSNt/8=
var request = new HttpRequestMessage(HttpMethod.Get, requestPath);
request.Headers.TryAddWithoutValidation("ACCESS-TIMESTAMP", timeStamp);
request.Headers.TryAddWithoutValidation("ACCESS-SIGN", signature);
//Act
var response = await http.Value.SendAsync(request);
//Assert
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
//"{\"epoch\":\"1555253501.225\",\"iso\":\"2019-04-14T14:51:41.225Z\",\"timestamp\":1555253501225}"
var server = JsonConvert.DeserializeObject<ServerTime>(json);
server.Should().NotBeNull();
server.Iso.Date.Should().Be(DateTime.Today);
}
long getEstimatedTimeStamp() {
return DateTime.Now.ToUnixTimeSeconds(); //custom extension method
}
}
public partial class ServerTime {
[JsonProperty("epoch")]
public string Epoch { get; set; }
[JsonProperty("iso")]
public DateTime Iso { get; set; }
[JsonProperty("timestamp")]
public long Timestamp { get; set; }
}
And was able to get a valid JSON response calling /api/v1/spot/public/time that I was able to deserialize for my assertion, even with the fake keys. Probably as this is the public API. This does prove that the URL called is correct.
When the request path is changed to
"/api/v1/spot/ccex/account/assets"
And tested for more secure private data from the API, the response is 400 Bad Request with the following content in the body of the response
{"message":"Encrypted key does not exist"}
which is as expected given that the keys I used were fake.
This gives me every indication that the API does in fact work as expected provided that you follow what is suggested in the linked documentation.
I wonder what I should pick as the answer due to this conflict of interest.
What happened is he go the extra mile of trying some API. I decided to create a new API key and post it here. It's read-only and can't possibly go wrong anyway. Before I posted here I try to run it once more expecting that it won't work like usual.
It turns out my code simply works. It seems that there are error in API key, secret, or password.
Here is the code that finally work
Protected Overrides Function getJsonPrivate(method As String, otherParameters() As Tuple(Of String, String)) As String
Dim base = "https://www.coinmex.pro"
Dim premethod = "/api/v1/spot/ccex/"
Dim longmethod = premethod + method
Dim timestampstring = (getEstimatedTimeStamp() / 1000).ToString
Dim stringtosign = timestampstring + "GET" + longmethod '1555154812.857GET/api/v1/spot/ccex/account/assets
Dim hasher = New System.Security.Cryptography.HMACSHA256(System.Text.Encoding.UTF8.GetBytes(_secret1)) '"43a90185f5b7ab25af045e9e64bac5dc745934f359f1806fcdd2a4af80ac2******
Dim sighashbyte = hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringtosign))
Dim signature = Convert.ToBase64String(sighashbyte) '"FIgrJFDOQctqnkOTyuv6+uTy6xw3OZiP4waC1u6P5LU="=
Dim url = base + longmethod 'https://www.coinmex.com/api/v1/spot/ccex/account/assets
'_apiKey1="cmx-1027e54e4723b09810576f8e7a5413**"
'_passphrase1= 1Us6&f%*K#QsqrYZ
'
Dim response = CookieAwareWebClient.downloadString1(url, "", {Tuple.Create("ACCESS-KEY", _apiKey1), Tuple.Create("ACCESS-SIGN", signature), Tuple.Create("ACCESS-TIMESTAMP", timestampstring), Tuple.Create("ACCESS-PASSPHRASE", _passphrase1)})
Return response
End Function
I am doing a .NET Core 2.0 App. I am calling a webService. I added a Reference to a local Service and call it from my Application.
ServiceReference1.QueryCalendarClient servicio = null;
ServiceReference1.ListCalendarDayTypeRequest request = new ServiceReference1.ListCalendarDayTypeRequest();
ServiceReference1.ListCalendarDayTypeResponse response = null;
var binding = new BasicHttpBinding();
binding.ReceiveTimeout = new TimeSpan(0, 25, 0);
binding.SendTimeout = new TimeSpan(0, 25, 0);
binding.MaxBufferSize = 2147483647;
binding.MaxReceivedMessageSize = 2147483647;
binding.Security = new BasicHttpSecurity
{
Mode = BasicHttpSecurityMode.TransportCredentialOnly,
Transport = new HttpTransportSecurity()
{
ClientCredentialType = HttpClientCredentialType.Basic
}
};
servicio = new ServiceReference1.QueryCalendarClient(binding, new EndpointAddress("http://WebBasica?wsdl"));
servicio.ClientCredentials.UserName.Password = "123456789";
servicio.ClientCredentials.UserName.UserName = "user";
response = new ServiceReference1.ListCalendarDayTypeResponse();
response = servicio.Method(request.CalendarInquireRequest_MT).Result;
I have an time Out Exception.
The request channel timed out while waiting for a reply after
00:24:58.3211575. Increase the timeout value passed to the call to
Request or increase the SendTimeout value on the Binding. The time
allotted to this operation may have been a portion of a longer
timeout.
Any timeOut I set, gave me a TimeOut error...
Where can I set the time out?
What I am missing?
Thank
I am using RabbitMQ .net client library to publish the messages to a RabbitMQ node in the following manner.
var factory = new ConnectionFactory
{
HostName = "localhost",
Port = 5672,
UserName = "guest",
Password = "guest",
VirtualHost = #"/"
};
_conn = factory.CreateConnection();
_channel = _conn.CreateModel();
_properties = _channel.CreateBasicProperties();
And then the below is being called in a loop
using (var memStream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(memStream, message);
var properties = _channel.CreateBasicProperties();
properties.Priority = Convert.ToByte((int) priority);
_channel.BasicPublish(String.Empty, _routeKey, properties, memStream.ToArray());
}
The above code is working fine with a medium load around 50-100 messages per second. But when I increase the number of messages to be published around 500 messages per second, the RabbitMQ node starts giving the below error and disconnects the channel.
Already closed: The AMQP operation was interrupted: AMQP close-reason, initiated by Peer, code=501, text="FRAME_ERROR - type 206, first 16 octets = <<31,0,60,0,40,0,0,6,115,101,110,115,111,114,16,115>>:
{invalid_frame_end_marker, 114}
", classId=0, methodId=0, cause=:
at RabbitMQ.Client.Impl.SessionBase.Transmit(Command cmd)
at RabbitMQ.Client.Impl.ModelBase.ModelSend(MethodBase method, ContentHeaderBase header, Byte[] body)
at RabbitMQ.Client.Impl.ModelBase.BasicPublish(String exchange, String routingKey, Boolean mandatory, Boolean immediate, IBasicProperties basicProperties, Byte[] body)
at RabbitMQ.Client.Impl.ModelBase.BasicPublish(String exchange, String routingKey, Boolean mandatory, IBasicProperties basicProperties, Byte[] body)
at RabbitMQ.Client.Impl.ModelBase.BasicPublish(String exchange, String routingKey, IBasicProperties basicProperties, Byte[] body)`
The size of the message with BinaryFormatter is around 5kb.
I am doing a project where i need to create a admit card for student who are appearing in examination. The pdf Generation part is working fine but my problem is i have to encode my pdf to Base64 format. I am not finding any solution. My code are given as bellow
public void downloadPdf() throws IOException, DocumentException {
System.out.println("hi i ma in");
resultList=examinationDetailsService.readAdmitCardData();
for(Object[] data:resultList)
{
personalDetails=(PersonalDetails)data[0];
System.out.println("name"+personalDetails.getApplicantName());
rollNoAssign=(RollNoAssign)data[1];
System.out.println("rollno"+rollNoAssign.getRollNo());
examDateAssign=(ExamDateAssign)data[2];
}
//Converting Date
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
String date = DATE_FORMAT.format(examDateAssign.getExaminationDate());
// Get the FacesContext
FacesContext facesContext = FacesContext.getCurrentInstance();
// Get HTTP response
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
// Set response headers
response.reset(); // Reset the response in the first place
response.setHeader("Content-Type", "application/pdf"); // Set only the content type
// Open response output stream
OutputStream responseOutputStream = response.getOutputStream();
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
PdfWriter.getInstance(document,response.getOutputStream());
document.open();
PdfPTable maintable = new PdfPTable(1);
maintable.setWidthPercentage(90);
maintable.setSpacingBefore(0f);
maintable.setSpacingAfter(0f);
Paragraph ph1 = new Paragraph();
ph1.add(new Chunk("\n\nGOVERNMENT OF ASSAM \nOFFICE OF THE ELECTRICAL LICENSING BOARD, ASSAM\n1", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL)));
//ph1.add(new Chunk("ST", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL)));
Chunk superScript = new Chunk("ST", FontFactory.getFont(FontFactory.TIMES_ROMAN, 8, Font.NORMAL));
superScript.setTextRise(5f);
ph1.add(superScript);
ph1.add(new Chunk(" FLOOR, WEST END BLOCK, HOUSEFED COMPLEX,DISPUR, GUWAHATI-781006, ASSAM.", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL)));
ph1.add(new Chunk("\n***\n", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD)));
ph1.add(new Chunk("\nADMIT CARD", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.BOLD)));
PdfPCell heading1 = new PdfPCell(ph1);
heading1.setBorder(0);
heading1.setHorizontalAlignment(Element.ALIGN_CENTER);
heading1.setVerticalAlignment(Element.ALIGN_CENTER);
maintable.addCell(heading1);
PdfPTable maintable1 = new PdfPTable(1);
maintable1.setWidthPercentage(87);
maintable1.setSpacingBefore(0f);
maintable1.setSpacingAfter(0f);
Paragraph ph2 = new Paragraph();
ph2.add(new Chunk("\n\nShri/Smti "+personalDetails.getApplicantName()+", Roll No. "+rollNoAssign.getRollNo()+" is hereby "
+ "allowed to appear in the examination for grant of Electrical Supervisor's Certificate of Competency "
+ "to be held at "+ rollNoAssign.getVenue().getName()
+ "as per schedule given below:", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL)));
ph2.add(new Chunk("\n\n Viva-voce", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.BOLD)));
ph2.add(new Chunk(" test on "+date+ " at 9 AM/12.30 PM ;", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL)));
ph2.add(new Chunk(" Written", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.BOLD)));
ph2.add(new Chunk(" test on __________ at 9 AM.", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL)));
ph2.add(new Chunk("\n\n\nPlease bring the followings with you while coming for the said examinations: \n"
+ "\n1.Original copy of Degree/Diploma/ITI Certificate/Supervisor's Certificate of Competency/"
+ "Workmen's Permit\n\n belonging to you and this Admit Card in original.\n"
+ "\n2.Detail experience certificate(s) relevant to the part(s) of Supervisor's examination applied for.\n"
+ "\n3.\n"
+ "\n\nNB: (a) No alteration is allowed in the entries on this Admit Card without the authority of the Board."
+ "\n (b) No expense(s) incurred by any candidate will be borne by the Board.\n\n\n", FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL)));
PdfPCell heading2 = new PdfPCell(ph2);
heading2.setBorder(0);
heading2.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
heading2.setVerticalAlignment(Element.ALIGN_CENTER);
maintable1.addCell(heading2);
PdfPTable maintable2 = new PdfPTable(2);
float[] columnWidths = new float[]{55f, 45f};
maintable2.setWidths(columnWidths);
maintable2.setWidthPercentage(84);
maintable2.setSpacingBefore(0f);
maintable2.setSpacingAfter(0f);
Paragraph ph31 = new Paragraph();
ph31.add(new Chunk("Details furnished by you in the application form and/or examination process are used by the Board"
+ " for further needful, hence, if you feel any correction(s) in the same is/are required, please get those done before"
+ " leaving the examination venue. The Board shall not be under any obligation of removing the difficulties arising later"
+ " on out of incorrect/improper information furnished by you or non-furnishing of required ones.\n", FontFactory.getFont(FontFactory.COURIER, 10, Font.NORMAL)));
PdfPCell heading31 = new PdfPCell(ph31);
heading31.setBorder(15);
heading31.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
heading31.setVerticalAlignment(Element.ALIGN_LEFT);
maintable2.addCell(heading31);
Paragraph ph32 = new Paragraph();
ph32.add(new Chunk("\n\n\n(Member Secretary)\nElectrical Licensing Board,\nAssam.", FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL)));
PdfPCell heading32 = new PdfPCell(ph32);
heading32.setBorder(0);
heading32.setHorizontalAlignment(Element.ALIGN_CENTER);
heading32.setVerticalAlignment(Element.ALIGN_CENTER);
maintable2.addCell(heading32);
document.add(maintable);
document.add(maintable1);
document.add(maintable2);
document.close();
/* // Read PDF contents
URL url = new URL(PDF_URL);
InputStream pdfInputStream = url.openStream();*/
// Read PDF contents and write them to the output
byte[] bytesBuffer = new byte[2048];
int bytesRead;
/* while ((bytesRead = pdfInputStream.read(bytesBuffer)) > 0) {
responseOutputStream.write(bytesBuffer, 0, bytesRead);
}
*/
Base64 encoder = new Base64();
byte[] decodedBytes = encoder.o
// Make sure that everything is out
responseOutputStream.write(decodedBytes);
responseOutputStream.flush();
// Close both streams
//pdfInputStream.close();
responseOutputStream.close();
// JSF doc:
// Signal the JavaServer Faces implementation that the HTTP response for this request has already been generated
// (such as an HTTP redirect), and that the request processing lifecycle should be terminated
// as soon as the current phase is completed.
facesContext.responseComplete();
}
Please give me any solution. i using itext
When I look at your code, I see:
PdfWriter.getInstance(document,response.getOutputStream());
Which means that you are instructing iText to write PDF bytes straight to the browser. This outputstream is closed at the moment you close the document.
I also see:
OutputStream responseOutputStream = response.getOutputStream();
I even see that you try adding stuff to this stream. This is impossible as the stream is already closed.
You need to create a ByteArrayOutputStream like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
And use this in the PdfWriter:
PdfWriter.getInstance(document, baos);
Now you can get the PDF bytes like this:
byte[] pdf = baos.toByteArray();
Now you can encode these bytes and send them to the output stream.
Encode:
Assuming that you are using org.apache.commons.codec.binary.Base64 as explained in the answer to Base64 Encoding in Java, you can do this:
byte[] base64 = Base64.encodeBase64(pdf);
(There are other ways to do this.)
Send to output stream:
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setContentType("application/pdf");
response.setContentLength(base64.length);
OutputStream os = response.getOutputStream();
os.write(base64);
os.flush();
os.close();
I faced to following problem with sending invitation in .net using exchange API
Send invitation in Israel timezone with start time =09/09/2013 4.30 Israel.
But it is displayed in outlook 09/09/2013 6.30 Israel.
It works properly for other time zones for example for EST.
Does anybody has any idea how to fix this?
Sample:
service.AutodiscoverUrl(loginForm.tbEmailAddress.Text, f);
TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Israel Standard Time");
Appointment appointment = new Appointment(service);
appointment.Subject = "subj";
appointment.Body = new MessageBody(BodyType.Text, "body");
appointment.StartTimeZone = timeZoneInfo;
appointment.Start = GetDateTime(new DateTime(2013, 09, 09, 04, 0, 0));
appointment.EndTimeZone = timeZoneInfo;
appointment.End = GetDateTime(new DateTime(2013, 09, 09, 04, 30, 0));
appointment.IsAllDayEvent = false;
appointment.Importance = Importance.Normal;
appointment.RequiredAttendees.Add("Lena", "email...");
appointment.Save(SendInvitationsMode.SendOnlyToAll);
...
private static DateTime GetDateTime(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute,
dateTime.Second, dateTime.Millisecond, DateTimeKind.Unspecified
);
}
I use Microsoft.Exchange.WebServices.dll 15.0.516.14
it's actually a known issue with Exchange EWS itself. Developer can only trust the date time returned without the timezone information, and the correct timezone for that time should be UTC always.