XOR ing more than 2 bytes
Hello,
As part of a device driver I am writing I need to create a checksum that is the XOR of all the bytes in the message. Does anyone know of a way to perform this?
I have tried this:
xor = a ^ b ^ c
but the program first creates XOR of a and b then XOR's the result with c which gives an incorrect answer.
Any help will be greatly appreciated,
Jason
But since XOR is an associative and commutative operation, it does not matter in which order the bytes are XORed. All of the following will give the same result:
xor = a ^ b ^ c;
xor = (a ^ b) ^ c;
xor = a ^ (b ^ c);
xor = (a ^ c) ^ b;
...Just XOR all the bytes with 0, and you'll get the proper result:
byte checksum = 0;
for (int j = 0; j < a.length; j++)
checksum ^= a[j];After this code is run, checksum will contain the XOR of all the bytes in the array a.
Similar Messages
-
How to insert more than 4000 bytes in BLOB column
Hi all,
My oracle version is Oracle Database 11g Enterprise Edition Release 11.2.0.3.0.
I have checked in google and in this forum also, but did not find the answer.
When inserting into less than 4000 bytes, it is inserting without any issues. If i am inserting more than that, it is throwing
error like this ORA-01460: unimplemented or unreasonable conversion requested.
Can anybody guide me how to do this or link.
Thanks in advance.
Thanks,
Paluser546710 wrote:
Hi,
Thank you very much for your reply.
Before, I have not worked with BLOB column, so I don't know much about its using. Currently, I am using direct
insert statement only. Its a normal stored procedure written in a package. I am calling this SP with other columns and
with this BLOB column. I am able to insert into table, if the inserted file is less than 4000 bytes. If it is more than that,
I am getting that problem.
Thanks,
VenuSQL variables can only hold 4000 bytes.
PL/SQL can hold up to 32767
I am getting that problem. 100% lacking in actionable detail
post code & COMPLETE error message & code -
How to get more than 256 bytes data
hello.
I use Schlumberger 32K Card�iJava Card 2.1�j.
Please tell me how to get more than 256 bytes data from the applet in the card!!
According to JCRE specification, need to use Get Response Command.
What is Get Response command?
Do I have to write processing of Get Response command to an applet?
Or JCRE processes Get Response command?
If knows, please tell me about!!
Thanks.Thanks for your response!!
I understand that I have to write processing of Get Response command to an applet.
But case of Schlumberger 32K card, when host send Get Response command to an applet, card reply 6F-00!?
I'm investigating now, and it seems that response is returned before applet processes Get Response command(CLA = 00, INS = C0).
Do JCRE perform the process of Get Response command? -
How to perform Text length more than 4000 bytes
I want to read each row from txt file
and used utl_file pacage to concat contents into a variable,
the variable datatype is varchar2(4000), so text length can't more than 4000 bytes,
but I wish get full text from txt file, How can I do?Thans! Detlev.
I have a code :
PROCEDURE read_file( path in varchar2, filename in varchar2, msg in out varchar2) AS
data_line varchar2(4000);
ifile utl_file.file_type;
BEGIN
ifile := utl_file.fopen(path,filename,'R');
LOOP
utl_file.get_line( ifile, data_line);
msg := msg | | rtrim(data_line);
END LOOP;
utl_file.fclose(ifile);
EXCEPTION
WHEN no_data_found THEN
utl_file.fclose(ifile);
END;
My question is
1. The msg length can't more than 4000
2. I use utl_raw.cast_to_raw function, that can't cast varchar2 to raw if varchar2 length more than 2048
3. If I want to change the data type varchar2 to raw,
the utl_raw.concat function can't use Loop ....end loop clause,
So that only use utl_raw.concat(ra1, ra2,ra3,ra4,ra5, ... ra12)
I want to concat all line to a raw datatype from text file , How can I do? -
Serial write takes unexpectedly long when more than 7 bytes are written
Hi,
My vi is attached.
As you see, it's very simple.
- output buffer fifo is set to 128 bytes, which is generously higher than my needs.
- my baudrate is 2.5 mpbs.
- I write string of 9 bytes such as 012345678, and the execution time of the vi is around 40 us.
I thought it's because of the blocking structure of the synchronous write, and I decided to switch to asynchronous
write, since I need to go above 20 kHz.
- when I switch to asynchronous write, it even gets worse, and I get ~58 us. it seems like asynchronous doesn't work at all.
so far, I explained my problem. I also did some simple experiments to debug the problem.
- when my string is shorter than 8 bytes, everything is beautiful, asynchronous write takes nearly 15 us.
when I enter an 8 bytes or longer string, it jumps up to 58 us again.
what am I doing wrong? I'm stuck here.
Gorkem Secer.
Attachments:
serialWrite_niForum_pic.png 19 KBThe driver might for a lot of reasons not want to or even can't fill up the 8 byte hardware FIFO buffer entirely. This could be for instance since it has to work around some bugs in certain hardware. It might not be necessary for the specific hardware revision in your system but that driver has to work for many different hardware systems.
The magnitude of timing control you try to achieve is simply beyond a software system if you require reliable and hard timings. It may be possible to achieve on a simpler but still powerful embedded system with custom made software drivers and RT OS but not on a more general purpose RT OS even if the hardware is pretty powerful. But such more custom made solutions would be more than a few magnitudes more expensive to develop.
You can keep barking up this tree but it is unlikely that NI can do much about it without redesigning parts of the RT system, which is pretty much out of question as they simply license it from Ardence/IntervalZero and only adapt it where it is strictly necessary to work with their hardware. Most likely their license doesn't even allow them to customize it at will in any other way than is strictly necessary to get it to work on their own hardware.
Your options are as far as I can see, to either rethink the timing requirements or adapt the software in such a way that the bigger delay won't be a problem or to go with a hardware solution based on an FPGA board or similar.
As to the difference of asynchronous write and synchronous that is mostly about what VISA API is called underneath. The LabVIEW function remains blocking for as long as is necessary to pass the data to the OS driver. In synchonous mode the LABVIEW VI calls the synchronous VISA API once and that simply waits until VISA returns from the function. For the asynchronous case LabVIEW calls the asynchonous VISA function and then keeps looping inside its own cooperative multithreading layer until VISA indicates that the asynchonous function has been performed. This is mostly for historical reasons when LabVIEW didn't have OS supported multithreading and all the multithreading happened in the cooperative LabVIEW code scheduler. Nowadays asynchonous VISA mode has almost no benefits anymore but genearlly will cause significantly more CPU load.
Rolf Kalbermatter
CIT Engineering Netherlands
a division of Test & Measurement Solutions -
How to encrypt more than 117 bytes with RSA?
Hi there,
I am struggling to encrypt more than 117 bytes of data with a 1024 bit RSA key.
If I try to encrypt (write to my OutputStreamWriter) 118 Bytes ("A"s) or more, the file I am writing to is just empty and I get an exception whe trying to read it.
I know the encryptable bytes (blocksize) are related to the key length: blocksize = keylength / 8 -11
I also know RSA encryption of large files is discouraged, because it is like 100x slower than for instance AES and was originally only intended to exchange symmetric keys.
Still I need to be able to asymmetrically encrypt at least 5kb of Data.
I am out of ideas here and have no understanding of why the block size is limited (i know from hours of "googling" that it is limited as described above though).
So, I would be very glad If somebody could point out a way how I could encrypt more than 117 bytes (without using a longer key of course).
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.Reader;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.security.PublicKey;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import javax.crypto.*;
public class strchrbty {
public static void main(String[] args) {
//generate Keys
PublicKey publicKey = null;
PrivateKey privateKey = null;
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.generateKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
//------ENCODE------
try {
//initialize cipher
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
OutputStream cos = new CipherOutputStream(new FileOutputStream("c:\\test.txt"), cipher);
Writer out = new OutputStreamWriter(cos);
// 1024 bit (key length) / 8 bytes - 11 bytes padding = 117 Bytes Data.
// for 118 Bytes (or more) Data: c:\\test.txt is empty annd no Data is read.
for(int i = 0; i<117; i++) {
out.write("A");
out.close();
cos.close();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
//------DECODE------
try {
StringBuffer buf = new StringBuffer();
Cipher cipher2 = Cipher.getInstance("RSA");
cipher2.init(Cipher.DECRYPT_MODE, privateKey);
//read char-wise
InputStream cis = new CipherInputStream(new FileInputStream("c:\\test.txt"), cipher2);
Reader in = new InputStreamReader(cis);
for(int c = in.read(); c != -1; c = in.read()) {
buf.append((char)c);
//output
System.out.println(buf.toString());
in.close();
cis.close();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}Regards.
Edited by: junghansmega on Sep 10, 2008 3:41 PM
Sorry about the bad autoformating.... It only occurrs in here, in my eclipse it looks fine =(junghansmega wrote:
Hi there,
I am struggling to encrypt more than 117 bytes of data with a 1024 bit RSA key.
If I try to encrypt (write to my OutputStreamWriter) 118 Bytes ("A"s) or more, the file I am writing to is just empty and I get an exception whe trying to read it.
Good, it should be painful.
>
Still I need to be able to asymmetrically encrypt at least 5kb of Data.
In this forum, 99.999% of the time this kind of claim is due to a lack of understanding of the role of public key cryptography.
I am out of ideas here and have no understanding of why the block size is limited (i know from hours of "googling" that it is limited as described above though).
It should not be difficult to break up the input into 117 byte chunks and encrypt each chunk through a newly initted cipher object. Of course you will have to be very careful in properly encoding the output. You might naively think that the output is always 128 bytes, but is that true? Might it be 127 bytes sometimes? Maybe even 126 bytes? -
German characters taking more than one bytes
Hi All,
I am trying to load a flat file (which I received in email), by SQL*loader into a table.
In few of the rows, not all, there are some German characters, like "hüri".
This data is going into a varchar2(30) column. In the text file, for this column (in the rows in question), there are 30 characters, **"If we count that special character as 1 character"**.
Means, if there was a normal English character in that string, instead of the German, this was a string of 30 characters and would be loaded without issues.
In this case, my load is failing. Error is, "ORA-12899: value too large for column SHORT_NAME (actual: 31, maximum: 30)".
Basically, that one character is taking space for more than 1 character in our database.
How can I get this character to fit in one character in database ???
Those on Unix, if I do the od command for that special character, I get this output.
od -c /tmp/a1
0000000 h 374 r i n \n
0000006
Details of my database are,
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for Linux: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
In v$parameter, I have these values,
nls_language=ENGLISH
nls_territory=UNITED KINGDOM
nls_sort=NULL
nls_date_language=NULL
nls_date_format=NULL
nls_currency=NULL
nls_numeric_characters=NULL
nls_iso_currency=NULL
nls_calendar=NULL
nls_time_format=NULL
nls_timestamp_format=NULL
nls_time_tz_format=NULL
nls_timestamp_tz_format=NULL
nls_dual_currency=NULL
nls_comp=BINARY
nls_length_semantics=BYTE
nls_nchar_conv_excp=FALSE
Heeeeelp ...
Thanks in advance.Try to run:
alter table <your table> modify <your VARCHAR2 column> varchar2(30 char);Example:
SQL> desc t
Name Null? Type
X NUMBER(38)
S VARCHAR2(10)
SQL> alter table t modify s varchar2(10 char);
Table altered.
SQL> desc t;
Name Null? Type
X NUMBER(38)
S VARCHAR2(10 CHAR)Edited by: P. Forstmann on 2 déc. 2010 19:48 -
More than 255 bytes in SO_NEW_DOCUMENT_ATT_SEND_API1
I know they are some posts about this topic already but I have read them all but I still don't have the solution. I hope someone could help me with this:
The problem is this: I have an internal table and I make an excell file of it which is mailed (sapmail) to the user who started the program. I all works fine except for the problem of the 255 limit. This happens because SOLISTI1 has an 255 limit. The excell attachment is mailed but it breaks after 255 characters (the total characters is about 500).
I know there are some solutions with TABLE_COMPRESS and TABLE_DECOMPRESS but I don't know on which moment you should compress or decompress which table! Below if my coding hope someone can help:
REPORT ZDTAFNAME_K.
tables: marc,
lips,
vbrp,
mara,
kna1,
vbak,
VBKD,
vbrk,
vbap,
vbep,
mvke,
mbew.
selection-screen: begin of block select with frame title text-f70.
select-options art for marc-matnr.
select-options abc for marc-abcin.
select-options fak for vbrp-vbeln default '20406070'.
Select-options dat for vbrp-erdat.
selection-screen: end of block select.
PARAMETERS: p_email TYPE somlreci1-receiver
DEFAULT '31dtg'.
data: rule(2) value '.,'.
data: begin of itab occurs 0,
deb like vbak-kunnr, "Debiteurennummer
debnaam like kna1-name1, "Naam debiteur
bestnr like vbkd-bstkd, "Bestelnr klant
artnr like marc-matnr, "Artikelnr
oms like lips-arktx, "Omschrijving
type like mara-groes, "Type
fab like lips-matkl, "Fabrikaat
faktuurdat like vbrp-erdat, "Faktuurdatum
faksrt like vbrk-fkart, "Faktuursoort
faktuur like vbrp-vbeln, "Faktuurnr
fakpos like vbrp-posnr, "Faktuurpositie
fakaantal(11) type c , "Faktuuraantal
fakeenh like vbrp-meins, "Faktuureenheid
fakwaarde(11) type c , "Faktuurwaarde
orddat like vbap-erdat, "Orderdatum
ordsrt like vbak-auart, "Ordersoort
verkoper like vbak-ernam, "Verkoper
ordnr like lips-vgbel, "Ordernr
ordnrpos like lips-vgpos, "Order positie
artklant like vbap-kdmat, "Artikelnr klant
ordaant(11) type c, "Order aantal
ordeenh like vbap-meins, "Order eenheid
ordwaarde(11) type c, "Nettowaarde orderpositie
postype like vbap-pstyv, "Positietype
gevlevdat like vbep-edatu, "Gevraagde leverdatum
levdat like lips-erdat, "Werkelijke leverdatum
levnr like lips-vbeln, "Leveringsnr
levpos like lips-posnr, "Levering positie
levaant(11) type c, "Leveringsaantal
leveenh like lips-meins, "Leveringseenheid
min(11) type c, "Bestelpunt
max(11) type c, "Max vrd
basiseenh like mara-meins, "Basiseenheid
abc like marc-abcin, "ABC Classificatie
artsoort like mara-mtart, "Artikelsoort
vkstatus(2) type c, "Verkoopstatus
ikstatus(2) type c, "Inkoopstatus
minlev(11) type c, "Min levereenheid
afrd(11) type c, "Afrondingswaarde
vprs(11) type c, "VPRS
vprseenh(11) type c, "VPRS eenheid
end of itab.
DATA: it_message TYPE STANDARD TABLE OF solisti1 INITIAL SIZE 0
WITH HEADER LINE.
DATA: it_attach TYPE STANDARD TABLE OF solisti1 INITIAL SIZE 0
WITH HEADER LINE.
DATA: t_packing_list LIKE sopcklsti1 OCCURS 0 WITH HEADER LINE,
t_contents LIKE solisti1 OCCURS 0 WITH HEADER LINE,
t_receivers LIKE somlreci1 OCCURS 0 WITH HEADER LINE,
t_attachment LIKE solisti1 OCCURS 0 WITH HEADER LINE,
t_object_header LIKE solisti1 OCCURS 0 WITH HEADER LINE,
w_cnt TYPE i,
w_sent_all(1) TYPE c,
w_doc_data LIKE sodocchgi1,
gd_error TYPE sy-subrc,
gd_reciever TYPE sy-subrc.
*START_OF_SELECTION
START-OF-SELECTION.
Retrieve sample data from table ekpo
PERFORM data_retrieval.
Populate table with detaisl to be entered into .xls file
PERFORM build_xls_data_table.
*END-OF-SELECTION
END-OF-SELECTION.
Populate message body text
perform populate_email_message_body.
Send file by email as .xls speadsheet
PERFORM send_file_as_email_attachment
tables it_message
it_attach
using p_email
'Example .xls documnet attachment'
'XLS'
'filename'
changing gd_error
gd_reciever.
Instructs mail send program for SAPCONNECT to send email(rsconn01)
PERFORM initiate_mail_execute_program.
*& Form DATA_RETRIEVAL
Retrieve data form EKPO table and populate itab it_ekko
FORM data_retrieval.
select * from vbrk client specified where
mandt = sy-mandt and
vbeln in fak and
erdat in dat and
fkart = 'F2'.
select * from vbrp client specified where
mandt = sy-mandt and
vbeln = vbrk-vbeln and
erdat in dat and
matnr in art.
select single * from marc client specified where
mandt = sy-mandt and
werks = 610 and
matnr = vbrp-matnr and
abcin in abc.
if sy-subrc = 0.
itab-levnr = vbrp-vgbel.
itab-levpos = vbrp-vgpos.
itab-faksrt = vbrk-fkart.
select single * from mara client specified where
mandt = sy-mandt and
matnr = marc-matnr.
if sy-subrc = 0.
itab-type = mara-groes.
itab-basiseenh = mara-meins.
endif.
select single * from mvke client specified where
mandt = sy-mandt and
matnr = marc-matnr.
if sy-subrc = 0.
itab-vkstatus = mvke-vmsta.
itab-minlev = mvke-scmng.
endif.
select single * from mbew client specified where
mandt = sy-mandt and
matnr = marc-matnr and
bwkey = 610.
if sy-subrc = 0.
itab-vprs = mbew-verpr.
itab-vprseenh = mbew-peinh.
endif.
select single * from vbak client specified where
mandt = sy-mandt and
vbeln = vbrp-aubel.
if sy-subrc = 0.
itab-deb = vbak-kunnr.
itab-ordsrt = vbak-auart.
endif.
select single * from vbap client specified where
mandt = sy-mandt and
vbeln = vbrp-aubel and
posnr = vbrp-aupos.
if sy-subrc = 0.
itab-verkoper = vbap-ernam.
itab-orddat = vbap-erdat.
itab-artklant = vbap-kdmat.
itab-ordaant := vbap-kwmeng.
itab-ordeenh = vbap-meins.
itab-ordwaarde := vbap-netwr.
itab-postype = vbap-pstyv.
endif.
select single * from vbep client specified where
mandt = sy-mandt and
vbeln = vbap-vbeln and
posnr = vbap-posnr and
etenr = '0001'.
if sy-subrc = 0.
itab-gevlevdat = vbep-edatu.
endif.
select single * from vbkd client specified where
mandt = sy-mandt and
vbeln = vbak-vbeln.
if sy-subrc = 0.
itab-bestnr = vbkd-bstkd.
endif.
select single * from lips client specified where
mandt = sy-mandt and
vbeln = vbrp-vgbel and
posnr = vbrp-vgpos.
if sy-subrc = 0.
itab-levdat = lips-erdat.
itab-levaant = lips-lfimg.
itab-leveenh = lips-meins.
else.
clear itab-levnr.
clear itab-levpos.
clear itab-levaant.
clear itab-levdat.
endif.
select single * from kna1 client specified where
mandt = sy-mandt and
kunnr = vbak-kunnr.
if sy-subrc = 0.
itab-debnaam = kna1-name1.
endif.
itab-artnr = marc-matnr.
itab-oms = vbrp-arktx.
itab-fab = vbrp-matkl.
itab-abc = marc-abcin.
itab-artsoort = mara-mtart.
itab-min = marc-minbe.
itab-max = marc-mabst.
itab-afrd = marc-bstrf.
itab-ikstatus = marc-mmsta.
itab-faktuur = vbrp-vbeln.
itab-fakpos = vbrp-posnr.
*UNPACK VBRP-FKIMG TO ITAB-FAKAANTAL.
*shift itab-fakaantal right by 3 places.
itab-fakaantal = vbrp-fkimg.
translate itab-fakaantal using rule.
itab-fakeenh = vbrp-meins.
itab-faktuurdat = vbrp-erdat.
*UNPACK VBRP-NETWR TO ITAB-FAKWAARDE.
*shift itab-FAKWAARDE right by 2 places.
itab-FAKWAARDE = vbrp-netwr.
Translate van velden
translate itab-fakwaarde using rule.
translate itab-fakaantal using rule.
translate itab-ordaant using rule.
translate itab-ordwaarde using rule.
translate itab-min using rule.
translate itab-max using rule.
translate itab-vkstatus using rule.
translate itab-ikstatus using rule.
itab-ordnr = vbrp-aubel.
itab-ordnrpos = vbrp-aupos.
append itab.
endif.
endselect. " Select * from vbrp.
endselect.
endform.
*& Form BUILD_XLS_DATA_TABLE
Build data table for .xls document
FORM build_xls_data_table.
CONSTANTS: con_cret TYPE x VALUE '0D', "OK for non Unicode
con_tab TYPE x VALUE '09'. "OK for non Unicode
*If you have Unicode check active in program attributes thnen you will
*need to declare constants as follows
*class cl_abap_char_utilities definition load.
*constants:
con_tab type c value cl_abap_char_utilities=>HORIZONTAL_TAB,
con_cret type c value cl_abap_char_utilities=>CR_LF.
CONCATENATE 'DEBNR' 'NAAM' 'BESTELNR'
'ARTNR' 'OMSCHRIJVING' 'TYPE'
'FABRIKAAT' 'FAKTUURDATUM' 'FAKSRT'
'FAKTUURNR' 'FAK.POS.' 'FAK.AANTAL'
'FAK.EENH' 'FAKTUUR WAARDE' 'ORDER DATUM'
'ORDSRT' 'VERKOPER' 'ORDERNR.' 'ORDER.POS.'
'ARTNR KLANT' 'ORDER AANTAL' 'ORDER EENH'
'ORDERWAARDE' 'POS.TYPE' 'GEVRAAGDE LEVDAT'
'WERKELIJKE LEVDAT' 'LEVERINGSNR' 'LEV.POS'
'LEV.AANTAL' 'LEV.EENH' 'BESTELPUNT'
'MAX VRD' 'BASISEENH' 'ABC' 'ARTSRT.'
'VK.STATUS' 'IK.STATUS' 'MIN.LEVEENH.'
'AFDRONDINGSWAARDE' 'VPRS' 'PER'
INTO it_attach SEPARATED BY con_tab.
CONCATENATE con_cret it_attach INTO it_attach.
APPEND it_attach.
LOOP AT ITAB.
CONCATENATE itab-deb itab-debnaam itab-bestnr itab-artnr
itab-oms itab-type itab-fab itab-faktuurdat
itab-faksrt itab-faktuur itab-fakpos
itab-fakaantal itab-fakeenh itab-fakwaarde
itab-orddat itab-ordsrt itab-verkoper itab-ordnr
itab-ordnrpos itab-artklant itab-ordaant
itab-ordeenh itab-ordwaarde itab-postype
itab-gevlevdat itab-levdat itab-levnr itab-levpos
itab-levaant itab-leveenh itab-min itab-max
itab-basiseenh itab-abc itab-artsoort itab-vkstatus
itab-ikstatus itab-minlev itab-afrd itab-vprs
itab-vprseenh
INTO it_attach SEPARATED BY con_tab.
CONCATENATE con_cret it_attach INTO it_attach.
APPEND it_attach.
ENDLOOP.
ENDFORM. " BUILD_XLS_DATA_TABLE
*& Form SEND_FILE_AS_EMAIL_ATTACHMENT
Send email
FORM send_file_as_email_attachment tables pit_message
pit_attach
using p_email
p_mtitle
p_format
p_filename
p_attdescription
p_sender_address
p_sender_addres_type
changing p_error
p_reciever.
DATA: ld_error TYPE sy-subrc,
ld_reciever TYPE sy-subrc,
ld_mtitle LIKE sodocchgi1-obj_descr,
ld_email LIKE somlreci1-receiver,
ld_format TYPE so_obj_tp ,
ld_attdescription TYPE so_obj_nam ,
ld_attfilename TYPE so_obj_des ,
ld_sender_address LIKE soextreci1-receiver,
ld_sender_address_type LIKE soextreci1-adr_typ,
ld_receiver LIKE sy-subrc.
ld_email = p_email.
ld_mtitle = p_mtitle.
ld_format = p_format.
ld_attdescription = p_attdescription.
ld_attfilename = p_filename.
ld_sender_address = p_sender_address.
ld_sender_address_type = p_sender_addres_type.
Fill the document data.
w_doc_data-doc_size = 1.
Populate the subject/generic message attributes
w_doc_data-obj_langu = sy-langu.
w_doc_data-obj_name = 'SAPRPT'.
w_doc_data-obj_descr = ld_mtitle .
w_doc_data-sensitivty = 'F'.
Fill the document data and get size of attachment
CLEAR w_doc_data.
READ TABLE it_attach INDEX w_cnt.
w_doc_data-doc_size =
( w_cnt - 1 ) * 255 + STRLEN( it_attach ).
w_doc_data-obj_langu = sy-langu.
w_doc_data-obj_name = 'SAPRPT'.
w_doc_data-obj_descr = ld_mtitle.
w_doc_data-sensitivty = 'F'.
CLEAR t_attachment.
REFRESH t_attachment.
t_attachment[] = pit_attach[].
Describe the body of the message
CLEAR t_packing_list.
REFRESH t_packing_list.
t_packing_list-transf_bin = space.
t_packing_list-head_start = 1.
t_packing_list-head_num = 0.
t_packing_list-body_start = 1.
DESCRIBE TABLE it_message LINES t_packing_list-body_num.
t_packing_list-doc_type = 'RAW'.
APPEND t_packing_list.
Create attachment notification
t_packing_list-transf_bin = 'X'.
t_packing_list-head_start = 1.
t_packing_list-head_num = 1.
t_packing_list-body_start = 1.
DESCRIBE TABLE t_attachment LINES t_packing_list-body_num.
t_packing_list-doc_type = ld_format.
t_packing_list-obj_descr = ld_attdescription.
t_packing_list-obj_name = ld_attfilename.
t_packing_list-doc_size = t_packing_list-body_num * 255.
APPEND t_packing_list.
Add the recipients email address
CLEAR t_receivers.
REFRESH t_receivers.
MOVE: SY-UNAME TO t_RECEIVERs-RECEIVER,
'X' TO t_RECEIVERs-EXPRESS,
'B' TO t_RECEIVERs-REC_TYPE.
APPEND t_RECEIVERs.
CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1'
EXPORTING
document_data = w_doc_data
put_in_outbox = 'X'
sender_address = ld_sender_address
sender_address_type = ld_sender_address_type
commit_work = 'X'
IMPORTING
sent_to_all = w_sent_all
TABLES
packing_list = t_packing_list
contents_bin = t_attachment
contents_txt = it_message
receivers = t_receivers
EXCEPTIONS
too_many_receivers = 1
document_not_sent = 2
document_type_not_exist = 3
operation_no_authorization = 4
parameter_error = 5
x_error = 6
enqueue_error = 7
OTHERS = 8.
Populate zerror return code
ld_error = sy-subrc.
Populate zreceiver return code
LOOP AT t_receivers.
ld_receiver = t_receivers-retrn_code.
ENDLOOP.
ENDFORM.
*& Form INITIATE_MAIL_EXECUTE_PROGRAM
Instructs mail send program for SAPCONNECT to send email.
FORM initiate_mail_execute_program.
WAIT UP TO 2 SECONDS.
SUBMIT rsconn01 WITH mode = 'INT'
WITH output = 'X'
AND RETURN.
ENDFORM. " INITIATE_MAIL_EXECUTE_PROGRAM
*& Form POPULATE_EMAIL_MESSAGE_BODY
Populate message body text
form populate_email_message_body.
REFRESH it_message.
it_message = 'Please find attached a list test ekpo records'.
APPEND it_message.
endform. " POPULATE_EMAIL_MESSAGE_BODYThanks Kunal Ghosh for your replies. I did try to condense it but it was still more than 255 characters.
I solved it by using chunks! I spend more than a week to solve this problem! The solution is so simple. Here's the new code for everybody who has the same problem:
REPORT ZDTAFNAME_K_ART no standard page heading line-size 250.
tables: marc,
lips,
vbrp,
mara,
kna1,
vbak,
VBKD,
vbrk,
vbap,
vbep,
mvke,
mbew.
selection-screen: begin of block select with frame title text-f70.
select-options art for marc-matnr.
select-options abc for marc-abcin.
select-options fak for vbrp-vbeln.
Select-options dat for vbrp-erdat.
select-options fsoort for vbrk-fkart.
select-options vest for marc-werks.
selection-screen: end of block select.
*parameters: p_email type somlreci1-receiver
DEFAULT '31dtg'.
data: p_email like somlreci1-receiver.
data: rule(2) value '.,'.
data: begin of itab occurs 0,
deb like vbak-kunnr, "Debiteurennummer
debnaam like kna1-name1, "Naam debiteur
bestnr like vbkd-bstkd, "Bestelnr klant
artnr like marc-matnr, "Artikelnr
oms like lips-arktx, "Omschrijving
type like mara-groes, "Type
fab like lips-matkl, "Fabrikaat
faktuurdat like vbrp-erdat, "Faktuurdatum
faksrt like vbrk-fkart, "Faktuursoort
faktuur like vbrp-vbeln, "Faktuurnr
fakpos like vbrp-posnr, "Faktuurpositie
fakaantal(11) type c , "Faktuuraantal
fakeenh like vbrp-meins, "Faktuureenheid
fakwaarde(11) type c , "Faktuurwaarde
orddat like vbap-erdat, "Orderdatum
ordsrt like vbak-auart, "Ordersoort
verkoper like vbak-ernam, "Verkoper
ordnr like lips-vgbel, "Ordernr
ordnrpos like lips-vgpos, "Order positie
artklant like vbap-kdmat, "Artikelnr klant
ordaant(11) type c, "Order aantal
ordeenh like vbap-meins, "Order eenheid
ordwaarde(11) type c, "Nettowaarde orderpositie
postype like vbap-pstyv, "Positietype
gevlevdat like vbep-edatu, "Gevraagde leverdatum
levdat like lips-erdat, "Werkelijke leverdatum
levnr like lips-vbeln, "Leveringsnr
levpos like lips-posnr, "Levering positie
levaant(11) type c, "Leveringsaantal
leveenh like lips-meins, "Leveringseenheid
min(11) type c, "Bestelpunt
max(11) type c, "Max vrd
basiseenh like mara-meins, "Basiseenheid
abc like marc-abcin, "ABC Classificatie
artsoort like mara-mtart, "Artikelsoort
vkstatus(2) type c, "Verkoopstatus
ikstatus(2) type c, "Inkoopstatus
minlev(11) type c, "Min levereenheid
afrd(11) type c, "Afrondingswaarde
vprs(11) type c, "VPRS
vprseenh(11) type c, "VPRS eenheid
end of itab.
DATA: it_message TYPE STANDARD TABLE OF solisti1 INITIAL SIZE 0
WITH HEADER LINE.
DATA: it_attach TYPE STANDARD TABLE OF solisti1 INITIAL SIZE 0
WITH HEADER LINE.
DATA: t_packing_list LIKE sopcklsti1 OCCURS 0 WITH HEADER LINE,
t_contents LIKE solisti1 OCCURS 0 WITH HEADER LINE,
t_receivers LIKE somlreci1 OCCURS 0 WITH HEADER LINE,
t_attachment LIKE solisti1 OCCURS 0 WITH HEADER LINE,
t_object_header LIKE solisti1 OCCURS 0 WITH HEADER LINE,
w_cnt TYPE i,
w_sent_all(1) TYPE c,
w_doc_data LIKE sodocchgi1,
gd_error TYPE sy-subrc,
gd_reciever TYPE sy-subrc.
*START_OF_SELECTION
START-OF-SELECTION.
Retrieve sample data from table ekpo
PERFORM data_retrieval.
Populate table with detaisl to be entered into .xls file
PERFORM build_xls_data_table.
*END-OF-SELECTION
END-OF-SELECTION.
Populate message body text
perform populate_email_message_body.
Send file by email as .xls speadsheet
PERFORM send_file_as_email_attachment
tables it_message
it_attach
using p_email
'Xls bestand afname per artikelsoort'
'XLS'
'filename'
changing gd_error
gd_reciever.
Instructs mail send program for SAPCONNECT to send email(rsconn01)
PERFORM initiate_mail_execute_program.
*& Form DATA_RETRIEVAL
Retrieve data form EKPO table and populate itab it_ekko
FORM data_retrieval.
select * from vbrk client specified where
mandt = sy-mandt and
vbeln in fak and
erdat in dat and
fkart in fsoort.
select * from vbrp client specified where
mandt = sy-mandt and
vbeln = vbrk-vbeln and
matnr in art.
select single * from marc client specified where
mandt = sy-mandt and
werks in vest and
matnr = vbrp-matnr and
abcin in abc.
if sy-subrc = 0.
itab-levnr = vbrp-vgbel.
itab-levpos = vbrp-vgpos.
itab-faksrt = vbrk-fkart.
select single * from mara client specified where
mandt = sy-mandt and
matnr = marc-matnr.
if sy-subrc = 0.
itab-type = mara-groes.
itab-basiseenh = mara-meins.
endif.
select single * from mvke client specified where
mandt = sy-mandt and
matnr = marc-matnr.
if sy-subrc = 0.
itab-vkstatus = mvke-vmsta.
itab-minlev = mvke-scmng.
endif.
select single * from mbew client specified where
mandt = sy-mandt and
matnr = marc-matnr and
bwkey = 610.
if sy-subrc = 0.
itab-vprs = mbew-verpr.
itab-vprseenh = mbew-peinh.
endif.
select single * from vbak client specified where
mandt = sy-mandt and
vbeln = vbrp-aubel.
if sy-subrc = 0.
itab-deb = vbak-kunnr.
itab-ordsrt = vbak-auart.
endif.
select single * from vbap client specified where
mandt = sy-mandt and
vbeln = vbrp-aubel and
posnr = vbrp-aupos.
if sy-subrc = 0.
itab-verkoper = vbap-ernam.
itab-orddat = vbap-erdat.
itab-artklant = vbap-kdmat.
itab-ordaant := vbap-kwmeng.
itab-ordeenh = vbap-meins.
itab-ordwaarde := vbap-netwr.
itab-postype = vbap-pstyv.
endif.
select single * from vbep client specified where
mandt = sy-mandt and
vbeln = vbap-vbeln and
posnr = vbap-posnr and
etenr = '0001'.
if sy-subrc = 0.
itab-gevlevdat = vbep-edatu.
endif.
select single * from vbkd client specified where
mandt = sy-mandt and
vbeln = vbak-vbeln.
if sy-subrc = 0.
itab-bestnr = vbkd-bstkd.
endif.
select single * from lips client specified where
mandt = sy-mandt and
vbeln = vbrp-vgbel and
posnr = vbrp-vgpos.
if sy-subrc = 0.
itab-levdat = lips-erdat.
itab-levaant = lips-lfimg.
itab-leveenh = lips-meins.
else.
clear itab-levnr.
clear itab-levpos.
clear itab-levaant.
clear itab-levdat.
endif.
select single * from kna1 client specified where
mandt = sy-mandt and
kunnr = vbak-kunnr.
if sy-subrc = 0.
itab-debnaam = kna1-name1.
endif.
itab-artnr = marc-matnr.
itab-oms = vbrp-arktx.
itab-fab = vbrp-matkl.
itab-abc = marc-abcin.
itab-artsoort = mara-mtart.
itab-min = marc-minbe.
itab-max = marc-mabst.
itab-afrd = marc-bstrf.
itab-ikstatus = marc-mmsta.
itab-faktuur = vbrp-vbeln.
itab-fakpos = vbrp-posnr.
*UNPACK VBRP-FKIMG TO ITAB-FAKAANTAL.
*shift itab-fakaantal right by 3 places.
itab-fakaantal = vbrp-fkimg.
translate itab-fakaantal using rule.
itab-fakeenh = vbrp-meins.
itab-faktuurdat = vbrp-erdat.
*UNPACK VBRP-NETWR TO ITAB-FAKWAARDE.
*shift itab-FAKWAARDE right by 2 places.
itab-FAKWAARDE = vbrp-netwr.
Translate van velden
translate itab-fakwaarde using rule.
translate itab-fakaantal using rule.
translate itab-ordaant using rule.
translate itab-ordwaarde using rule.
translate itab-min using rule.
translate itab-max using rule.
translate itab-vkstatus using rule.
translate itab-ikstatus using rule.
translate itab-VPRS using rule.
translate itab-vprseenh using rule.
translate itab-levaant using rule.
translate itab-minlev using rule.
translate itab-afrd using rule.
itab-ordnr = vbrp-aubel.
itab-ordnrpos = vbrp-aupos.
append itab.
clear itab.
endif.
endselect. " Select * from vbrp.
endselect. " Select * from vbrk.
endform.
*& Form BUILD_XLS_DATA_TABLE
Build data table for .xls document
FORM build_xls_data_table.
CONSTANTS: con_cret TYPE x VALUE '0D', "OK for non Unicode
con_tab TYPE x VALUE '09'. "OK for non Unicode
*If you have Unicode check active in program attributes thnen you will
*need to declare constants as follows
*class cl_abap_char_utilities definition load.
*constants:
con_tab type c value cl_abap_char_utilities=>HORIZONTAL_TAB,
con_cret type c value cl_abap_char_utilities=>CR_LF.
<b>
CONCATENATE 'DEBNR' 'NAAM' 'BESTELNR'
'ARTNR' 'OMSCHRIJVING' 'TYPE'
'FABRIKAAT' 'FAKTUURDATUM' 'FAKSRT'
'FAKTUURNR' 'FAK.POS.' 'FAK.AANTAL'
'FAK.EENH' 'FAKTUUR WAARDE' 'ORDER DATUM'
'ORDSRT' 'VERKOPER' 'ORDERNR.' 'ORDER.POS.'
'ARTNR KLANT' 'ORDER AANTAL'
INTO it_attach SEPARATED BY con_tab.
CONCATENATE con_cret it_attach INTO it_attach.
APPEND it_attach.
CONCATENATE con_tab 'ORDER EENH' 'ORDERWAARDE'
'POS.TYPE' 'GEVRAAGDE LEVDAT'
'WERKELIJKE LEVDAT' 'LEVERINGSNR' 'LEV.POS'
'LEV.AANTAL' 'LEV.EENH' 'BESTELPUNT'
'MAX VRD' 'BASISEENH' 'ABC' 'ARTSRT.'
'VK.STATUS' 'IK.STATUS' 'MIN.LEVEENH.'
'AFDRONDINGSWAARDE' 'VPRS' 'PER'
INTO it_attach SEPARATED BY con_tab.
APPEND it_attach.
LOOP AT ITAB.
CONCATENATE itab-deb itab-debnaam itab-bestnr itab-artnr
itab-oms itab-type itab-fab itab-faktuurdat
itab-faksrt itab-faktuur itab-fakpos
itab-fakaantal itab-fakeenh itab-fakwaarde
itab-orddat itab-ordsrt itab-verkoper itab-ordnr
itab-ordnrpos itab-artklant itab-ordaant
INTO it_attach SEPARATED BY con_tab.
CONCATENATE Con_cret it_attach INTO it_attach.
APPEND it_attach.
CONCATENATE con_tab itab-ordeenh itab-ordwaarde itab-postype
itab-gevlevdat itab-levdat itab-levnr itab-levpos
itab-levaant itab-leveenh itab-min itab-max
itab-basiseenh itab-abc itab-artsoort itab-vkstatus
itab-ikstatus itab-minlev itab-afrd itab-vprs
itab-vprseenh
INTO it_attach SEPARATED BY con_tab.
APPEND it_attach.
ENDLOOP.</b>
ENDFORM. " BUILD_XLS_DATA_TABLE
*& Form SEND_FILE_AS_EMAIL_ATTACHMENT
Send email
FORM send_file_as_email_attachment tables pit_message
pit_attach
using p_email
p_mtitle
p_format
p_filename
p_attdescription
p_sender_address
p_sender_addres_type
changing p_error
p_reciever.
DATA: ld_error TYPE sy-subrc,
ld_reciever TYPE sy-subrc,
ld_mtitle LIKE sodocchgi1-obj_descr,
ld_email LIKE somlreci1-receiver,
ld_format TYPE so_obj_tp ,
ld_attdescription TYPE so_obj_nam ,
ld_attfilename TYPE so_obj_des ,
ld_sender_address LIKE soextreci1-receiver,
ld_sender_address_type LIKE soextreci1-adr_typ,
ld_receiver LIKE sy-subrc.
ld_email = p_email.
ld_mtitle = p_mtitle.
ld_format = p_format.
ld_attdescription = p_attdescription.
ld_attfilename = p_filename.
ld_sender_address = p_sender_address.
ld_sender_address_type = p_sender_addres_type.
Fill the document data.
w_doc_data-doc_size = 1.
Populate the subject/generic message attributes
w_doc_data-obj_langu = sy-langu.
w_doc_data-obj_name = 'SAPRPT'.
w_doc_data-obj_descr = ld_mtitle .
w_doc_data-sensitivty = 'F'.
Fill the document data and get size of attachment
CLEAR w_doc_data.
READ TABLE it_attach INDEX w_cnt.
w_doc_data-doc_size =
( w_cnt - 1 ) * 255 + STRLEN( it_attach ).
w_doc_data-obj_langu = sy-langu.
w_doc_data-obj_name = 'SAPRPT'.
w_doc_data-obj_descr = ld_mtitle.
w_doc_data-sensitivty = 'F'.
CLEAR t_attachment.
REFRESH t_attachment.
t_attachment[] = pit_attach[].
Describe the body of the message
CLEAR t_packing_list.
REFRESH t_packing_list.
t_packing_list-transf_bin = space.
t_packing_list-head_start = 1.
t_packing_list-head_num = 0.
t_packing_list-body_start = 1.
DESCRIBE TABLE it_message LINES t_packing_list-body_num.
t_packing_list-doc_type = 'RAW'.
APPEND t_packing_list.
Create attachment notification
t_packing_list-transf_bin = 'X'.
t_packing_list-head_start = 1.
t_packing_list-head_num = 1.
t_packing_list-body_start = 1.
DESCRIBE TABLE t_attachment LINES t_packing_list-body_num.
t_packing_list-doc_type = ld_format.
t_packing_list-obj_descr = ld_attdescription.
t_packing_list-obj_name = ld_attfilename.
t_packing_list-doc_size = t_packing_list-body_num * 255.
APPEND t_packing_list.
Add the recipients email address
CLEAR t_receivers.
REFRESH t_receivers.
MOVE: SY-UNAME TO t_RECEIVERs-RECEIVER,
'X' TO t_RECEIVERs-EXPRESS,
'B' TO t_RECEIVERs-REC_TYPE.
APPEND t_RECEIVERs.
CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1'
EXPORTING
document_data = w_doc_data
put_in_outbox = 'X'
sender_address = ld_sender_address
sender_address_type = ld_sender_address_type
commit_work = 'X'
IMPORTING
sent_to_all = w_sent_all
TABLES
packing_list = t_packing_list
contents_bin = t_attachment
contents_txt = it_message
receivers = t_receivers
EXCEPTIONS
too_many_receivers = 1
document_not_sent = 2
document_type_not_exist = 3
operation_no_authorization = 4
parameter_error = 5
x_error = 6
enqueue_error = 7
OTHERS = 8.
Populate zerror return code
ld_error = sy-subrc.
Populate zreceiver return code
LOOP AT t_receivers.
ld_receiver = t_receivers-retrn_code.
ENDLOOP.
ENDFORM.
*& Form INITIATE_MAIL_EXECUTE_PROGRAM
Instructs mail send program for SAPCONNECT to send email.
FORM initiate_mail_execute_program.
WAIT UP TO 2 SECONDS.
SUBMIT rsconn01 WITH mode = 'INT'
WITH output = 'X'
AND RETURN.
ENDFORM. " INITIATE_MAIL_EXECUTE_PROGRAM
*& Form POPULATE_EMAIL_MESSAGE_BODY
Populate message body text
form populate_email_message_body.
REFRESH it_message.
it_message = 'Deze mail is automatisch gemaakt door transactie ZAKA'.
APPEND it_message.
endform. " POPULATE_EMAIL_MESSAGE_BODY -
OS is Windows 2000. Problem is with websites in general. Pictures are frequently missing or are blank unless download is attempted more than once. Ads are frequently downloaded as blank.areas. No problems downloading text only sites. PDF file downloads are sometimes stopped.
When web pages are printed using HP software, sometimes the printing is "padded" before and after with blank pages, or the range of pages is incomplete both in the printing review and the printed results. This does not happen when printing from the IE browsers supported by the OS.It is possible that your security software (firewall, anti-virus) blocks or restricts Firefox or the plugin-container process without informing you, possibly after detecting changes (update) to the Firefox program.
Remove all rules for Firefox and the plugin-container from the permissions list in the firewall and let your firewall ask again for permission to get full, unrestricted, access to internet for Firefox and the plugin-container process and the updater process.
See:
*https://support.mozilla.org/kb/Server+not+found
*https://support.mozilla.org/kb/Firewalls
*https://support.mozilla.org/kb/fix-problems-connecting-websites-after-updating
Do a malware check with several malware scanning programs on the Windows computer.<br>
Please scan with all programs because each program detects different malware.<br>
All these programs have free versions.
Make sure that you update each program to get the latest version of their databases before doing a scan.
*Malwarebytes' Anti-Malware:<br>http://www.malwarebytes.org/mbam.php
*AdwCleaner:<br>http://www.bleepingcomputer.com/download/adwcleaner/<br>http://www.softpedia.com/get/Antivirus/Removal-Tools/AdwCleaner.shtml
*SuperAntispyware:<br>http://www.superantispyware.com/
*Microsoft Safety Scanner:<br>http://www.microsoft.com/security/scanner/en-us/default.aspx
*Windows Defender:<br>http://windows.microsoft.com/en-us/windows/using-defender
*Spybot Search & Destroy:<br>http://www.safer-networking.org/en/index.html
*Kasperky Free Security Scan:<br>http://www.kaspersky.com/security-scan
You can also do a check for a rootkit infection with TDSSKiller.
*Anti-rootkit utility TDSSKiller:<br>http://support.kaspersky.com/5350?el=88446
See also:
*"Spyware on Windows": http://kb.mozillazine.org/Popups_not_blocked -
ANY ONE CAN TELLM WT WE HAVE TO DO IF THE SEGMENT HAVING MORE THAN 1000 BYTESOF DATA IN IDOCS
Moderator message : Search for available information, do not use all capitals. Thread locked.
Edited by: Vinod Kumar on Aug 23, 2011 2:33 PMHi,
The EDIDD (Data record (IDoc)) has a component SDATA which is of length 1000 LCHR. I think that is the maximum limit provided by SAP. I would say if the data in the IDOC is more than that we rather split it in two different segments. -
More than one ipod / iphone sync'ing
If we own more than one ipod / iphone (two of each) how do we sync without getting each other's apps, etc.
The issue here is Contacts - my 3000 contacts built over 14 (yes, 14) years on PDAs have been - merged? - with my wife's and we each have both. She has mine anyway and it is driving her nuts. Is there a way to sort this out? To clarify one step further - she broke iPhone, got new iPhone, and it was in syncing this new phone that she acquired my contacts. So, her ORIGINAL iPhone is still listed as a device in iTunes and I wonder if (and suspect that) her isolated/original contact list is still associated with that first iPhone. So, how can I make her current phone be recognized instead as that old phone and back itself up with that old iphone's data (contacts)? Muchg appreciate your help here.
-
Sync ing iPod to more than one computer?
Am I able to sync my iPod Touch 4th generation to a 2nd computer with iTunes, or will I loose everything on the iPod?
You can only sync with one computer/iTunes library. However, you manage music with more than one computer.. See:
Using iPhone, iPad, or iPod with multiple computers -
Not able to create More than 1 Partition in USB Drive using kernel32 and DeviceIoControl
I have successfully created 2 or more partitions in USB drive using DeviceIoControl in C++. Now I am trying to convert this code into C# using kernel32 and DeviceIoControl. But I am not getting more than 1 partition. Can anybody tell me what is wrong
with this code?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace PartitionWrapper
public class IOWrapper
public static bool CreatePartitions(string selectedDrive)
bool RetCode = false;
try
bool bSuccess = false;
uint dwBytesReturned = 0;
IntPtr hDisk = OpenVolume(selectedDrive);
if (hDisk == null || hDisk == FSConstants.INVALID_HANDLE_VALUE)
RetCode = false;
goto FINAL;
bSuccess = FSStructures.DeviceIoControl(hDisk, FSConstants.IOCTL_DISK_DELETE_DRIVE_LAYOUT, IntPtr.Zero, 0, default(IntPtr), default(uint), ref dwBytesReturned);
// Get the partition information
uint PartitionInfomations = (uint)(Marshal.SizeOf(typeof(FSStructures.DRIVE_LAYOUT_INFORMATION_EX)) + 3 * Marshal.SizeOf(typeof(FSStructures.PARTITION_INFORMATION_EX)));
byte[] DBuffer = new byte[PartitionInfomations];
GCHandle handle = GCHandle.Alloc(DBuffer, GCHandleType.Pinned);
FSStructures.DRIVE_LAYOUT_INFORMATION_EX pDriveLayout = (FSStructures.DRIVE_LAYOUT_INFORMATION_EX)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(FSStructures.DRIVE_LAYOUT_INFORMATION_EX));
IntPtr pDriveLayoutPtr = Marshal.AllocHGlobal(Marshal.SizeOf(pDriveLayout));
Marshal.StructureToPtr(pDriveLayout, pDriveLayoutPtr, false);
// bSuccess = FSStructures.DeviceIoControl(hDisk, FSConstants.IOCTL_DISK_GET_DRIVE_LAYOUT_EX, default(IntPtr), default(uint), pDriveLayoutPtr, PartitionInfomations, ref dwBytesReturned);
pDriveLayout = (FSStructures.DRIVE_LAYOUT_INFORMATION_EX)Marshal.PtrToStructure(pDriveLayoutPtr, typeof(FSStructures.DRIVE_LAYOUT_INFORMATION_EX));
if (bSuccess || dwBytesReturned != PartitionInfomations)
RetCode = true;
else { RetCode = false; goto FINAL; }
pDriveLayout.PartitionEntry = new FSStructures.PARTITION_INFORMATION_EX[0x16];
pDriveLayout.PartitionStyle = FSStructures.PARTITION_STYLE.MasterBootRecord;
pDriveLayout.PartitionCount = 4;
pDriveLayout.DriveLayoutInformatiton.Mbr.Signature = 0xA4B57300;
pDriveLayout.PartitionEntry[0] = new FSStructures.PARTITION_INFORMATION_EX();
pDriveLayout.PartitionEntry[0].PartitionStyle = FSStructures.PARTITION_STYLE.MasterBootRecord;
pDriveLayout.PartitionEntry[0].Mbr.BootIndicator = true;
pDriveLayout.PartitionEntry[0].Mbr.RecognizedPartition = true;
pDriveLayout.PartitionEntry[0].Mbr.PartitionType = 0x0B;
pDriveLayout.PartitionEntry[0].PartitionNumber = 1;
pDriveLayout.PartitionEntry[0].StartingOffset = 32256;
pDriveLayout.PartitionEntry[0].PartitionLength = 3221225472;
pDriveLayout.PartitionEntry[0].RewritePartition = true;
pDriveLayout.PartitionEntry[0].Mbr.HiddenSectors = 32256 / 512;
pDriveLayout.PartitionEntry[1] = new FSStructures.PARTITION_INFORMATION_EX();
pDriveLayout.PartitionEntry[1].PartitionStyle = FSStructures.PARTITION_STYLE.MasterBootRecord;
pDriveLayout.PartitionEntry[1].Mbr.BootIndicator = false;
pDriveLayout.PartitionEntry[1].Mbr.RecognizedPartition = true;
pDriveLayout.PartitionEntry[1].Mbr.PartitionType = 0x0B;
pDriveLayout.PartitionEntry[1].PartitionNumber = 2;
pDriveLayout.PartitionEntry[1].StartingOffset = 32256 + 3221225472;
pDriveLayout.PartitionEntry[1].PartitionLength = 2147483648; //2147483648;//3221225472;
pDriveLayout.PartitionEntry[1].RewritePartition = true;
pDriveLayout.PartitionEntry[1].Mbr.HiddenSectors = 32256 / 512;
for (int i = 0; i < pDriveLayout.PartitionEntry.Length; i++)
pDriveLayout.PartitionEntry[i].RewritePartition = true;
try
bSuccess = FSStructures.DeviceIoControl(hDisk, FSConstants.IOCTL_DISK_SET_DRIVE_LAYOUT_EX, ref pDriveLayout, PartitionInfomations, default(IntPtr), default(uint), ref dwBytesReturned);
catch (Exception ex)
if (bSuccess)
RetCode = true;
else { RetCode = false; }
bSuccess = FSStructures.DeviceIoControl(hDisk, FSConstants.IOCTL_DISK_UPDATE_PROPERTIES, IntPtr.Zero, 0, default(IntPtr), default(uint), ref dwBytesReturned);
if (bSuccess)
RetCode = true;
else { RetCode = false; }
FINAL:
// Close the disk handle.
if (hDisk != null && hDisk != FSConstants.INVALID_HANDLE_VALUE)
FSStructures.CloseHandle(hDisk);
catch { return false; }
return RetCode;
private static IntPtr OpenVolume(string DeviceName)
try
IntPtr hDevice;
hDevice = FSStructures.CreateFile(
@"\\.\" + DeviceName,
FSConstants.GENERIC_EXECUTE | FSConstants.GENERIC_READ | FSConstants.GENERIC_WRITE | FSConstants.FILE_SHARE_READ | FSConstants.FILE_SHARE_WRITE,
FSConstants.FILE_SHARE_WRITE,
IntPtr.Zero,
FSConstants.OPEN_EXISTING,
0,
IntPtr.Zero);
if ((int)hDevice == -1)
throw new Exception(Marshal.GetLastWin32Error().ToString());
return hDevice;
catch { return FSConstants.INVALID_HANDLE_VALUE; }
internal static class FSConstants
public const uint FILE_SHARE_READ = 0x00000001;
public const uint FILE_SHARE_WRITE = 0x00000002;
public const uint OPEN_EXISTING = 3;
public const int GENERIC_EXECUTE = 0x10000000;
public const uint GENERIC_READ = (0x80000000);
public const uint GENERIC_WRITE = (0x40000000);
public static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
public const uint IOCTL_DISK_GET_DRIVE_LAYOUT_EX = 0x00070050;
public const uint IOCTL_DISK_SET_DRIVE_LAYOUT_EX = 0x7C054;
public const int IOCTL_DISK_UPDATE_PROPERTIES = 0x70140;
public const int IOCTL_DISK_DELETE_DRIVE_LAYOUT = 0x0007c010;
public const int IOCTL_DISK_CREATE_DISK = 0x7C058;
internal static class FSStructures
[DllImport("kernel32.dll", EntryPoint = "CreateFile", SetLastError = true)]
public static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
[Optional]ref DRIVE_LAYOUT_INFORMATION_EX lpInBuffer,
uint nInBufferSize,
[Optional] [Out] IntPtr lpOutBuffer,
uint nOutBufferSize,
[Optional] ref uint lpBytesReturned,
[Optional] IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
IntPtr lpInBuffer,
uint nInBufferSize,
[Optional] [Out] IntPtr lpOutBuffer,
uint nOutBufferSize,
[Optional] ref uint lpBytesReturned,
[Optional] IntPtr lpOverlapped);
[StructLayout(LayoutKind.Sequential)]
public struct DRIVE_LAYOUT_INFORMATION_EX
public PARTITION_STYLE PartitionStyle;
public int PartitionCount;
public DRIVE_LAYOUT_INFORMATION_UNION DriveLayoutInformatiton;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 0x16)]
public PARTITION_INFORMATION_EX[] PartitionEntry;
[StructLayout(LayoutKind.Sequential)]
public struct PARTITION_INFORMATION_EX
[MarshalAs(UnmanagedType.U4)]
public PARTITION_STYLE PartitionStyle;
public long StartingOffset;
public long PartitionLength;
public int PartitionNumber;
public bool RewritePartition;
public PARTITION_INFORMATION_MBR Mbr;
public PARTITION_INFORMATION_GPT Gpt;
[StructLayout(LayoutKind.Sequential)]
public struct PARTITION_INFORMATION_MBR
public byte PartitionType;
[MarshalAs(UnmanagedType.U1)]
public bool BootIndicator;
[MarshalAs(UnmanagedType.U1)]
public bool RecognizedPartition;
public uint HiddenSectors;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct PARTITION_INFORMATION_GPT
public Guid PartitionType;
public Guid PartitionId;
[MarshalAs(UnmanagedType.U8)]
public EFIPartitionAttributes Attributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)]
public string Name;
[Flags]
public enum EFIPartitionAttributes : ulong
GPT_ATTRIBUTE_PLATFORM_REQUIRED = 0x0000000000000001,
LegacyBIOSBootable = 0x0000000000000004,
GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER = 0x8000000000000000,
GPT_BASIC_DATA_ATTRIBUTE_HIDDEN = 0x4000000000000000,
GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY = 0x2000000000000000,
GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY = 0x1000000000000000
[StructLayout(LayoutKind.Explicit)]
public struct DRIVE_LAYOUT_INFORMATION_UNION
[FieldOffset(0)]
public DRIVE_LAYOUT_INFORMATION_MBR Mbr;
[FieldOffset(0)]
public DRIVE_LAYOUT_INFORMATION_GPT Gpt;
[StructLayout(LayoutKind.Sequential)]
public struct DRIVE_LAYOUT_INFORMATION_GPT
public Guid DiskId;
public long StartingUsableOffset;
public long UsableLength;
public int MaxPartitionCount;
[StructLayout(LayoutKind.Sequential)]
public struct DRIVE_LAYOUT_INFORMATION_MBR
public uint Signature;
public enum PARTITION_STYLE : int
MasterBootRecord = 0,
GuidPartitionTable = 1,
Raw = 2Hello,
in the links below you can found many informations to help you:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa365730(v=vs.85).aspx
http://www.codeproject.com/Articles/696388/Recover-Data-From-Corrupted-Drives-File-Systems-FA
http://www.functionx.com/vcsharp/fileprocessing/drives.htm
http://forums.codeguru.com/showthread.php?548305-partitioning-USB-Falsh-drive
http://forums.codeguru.com/showthread.php?548169-USB-Flash-drive-Partitioning -
Help! Kernel_task more than 300% of CPU and extremely laggy
Hi, I am using MacBook Pro 13 inch Early 2011 and using OS X 10.9.2 Mavericks
It has been a few days that my computer was running extremely slow and I need to hold the power button for 10 seconds for it to boot (if i press it once the white power light on the mac body would only light for a while then turns off again)
I did not know what triggered it, it was just like thay when i tried booting by mac
I checked activity monitor and the kernel_task was actually taking up more than 300% of my cpu!
I googled for answers but I can't find any. Is it due to third party software?
Furthermore, when I safe boot the kernel_task would actually be low and the speed will revert back to normal.
Please help me
Thank you1. This procedure is a diagnostic test. It changes nothing, for better or worse, and therefore will not, in itself, solve the problem. But with the aid of the test results, the solution may take a few minutes, instead of hours or days.
Don't be put off merely by the seeming complexity of these instructions. The process is much less complicated than the description. You do harder tasks with the computer all the time.
2. If you don't already have a current backup, back up all data before doing anything else. The backup is necessary on general principle, not because of anything in the test procedure. Backup is always a must, and when you're having any kind of trouble with the computer, you may be at higher than usual risk of losing data, whether you follow these instructions or not.
There are ways to back up a computer that isn't fully functional. Ask if you need guidance.
3. Below are instructions to run a UNIX shell script, a type of program. As I wrote above, it changes nothing. It doesn't send or receive any data on the network. All it does is to generate a human-readable report on the state of the computer. That report goes nowhere unless you choose to share it. If you prefer, you can read it yourself without disclosing the contents to me or anyone else.
You should be wondering whether you can believe me, and whether it's safe to run a program at the behest of a stranger. In general, no, it's not safe and I don't encourage it.
In this case, however, there are a couple of ways for you to decide whether the program is safe without having to trust me. First, you can read it. Unlike an application that you download and click to run, it's transparent, so anyone with the necessary skill can verify what it does.
You may not be able to understand the script yourself. But variations of the script have been posted on this website thousands of times over a period of years. The site is hosted by Apple, which does not allow it to be used to distribute harmful software. Any one of the millions of registered users could have read the script and raised the alarm if it was harmful. Then I would not be here now and you would not be reading this message.
Nevertheless, if you can't satisfy yourself that these instructions are safe, don't follow them. Ask for other options.
4. Here's a summary of what you need to do, if you choose to proceed:
☞ Copy a line of text in this window to the Clipboard.
☞ Paste into the window of another application.
☞ Wait for the test to run. It usually takes a few minutes.
☞ Paste the results, which will have been copied automatically, back into a reply on this page.
The sequence is: copy, paste, wait, paste again. You don't need to copy a second time. Details follow.
5. You may have started the computer in "safe" mode. Preferably, these steps should be taken in “normal” mode, under the conditions in which the problem is reproduced. If the system is now in safe mode and works well enough in normal mode to run the test, restart as usual. If you can only test in safe mode, do that.
6. If you have more than one user, and the one affected by the problem is not an administrator, then please run the test twice: once while logged in as the affected user, and once as an administrator. The results may be different. The user that is created automatically on a new computer when you start it for the first time is an administrator. If you can't log in as an administrator, test as the affected user. Most personal Macs have only one user, and in that case this section doesn’t apply. Don't log in as root.
7. The script is a single long line, all of which must be selected. You can accomplish this easily by triple-clicking anywhere in the line. The whole line will highlight, though you may not see all of it in the browser window, and you can then copy it. If you try to select the line by dragging across the part you can see, you won't get all of it.
Triple-click anywhere in the line of text below on this page to select it:
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/libexec;clear;cd;p=(Software Hardware Memory Diagnostics Power FireWire Thunderbolt USB Fonts SerialATA 4 1000 25 5120 KiB/s 1024 85 \\b%% 20480 1 MB/s 25000 ports ' com.clark.\* \*dropbox \*GoogleDr\* \*k.AutoCAD\* \*k.Maya\* vidinst\* ' DYLD_INSERT_LIBRARIES\ DYLD_LIBRARY_PATH -86 ` route -n get default|awk '/e:/{print $2}' ` 25 N\\/A down up 102400 25600 recvfrom sendto CFBundleIdentifier 25 25 25 1000 MB com.apple.AirPortBaseStationAgent 464843899 51 5120 files );N5=${#p[@]};p[N5]=` networksetup -listnetworkserviceorder|awk ' NR>1 { sub(/^\([0-9]+\) /,"");n=$0;getline;} $NF=="'${p[26]}')" { sub(/.$/,"",$NF);print n;exit;} ' `;f=('\n%s: %s\n' '\n%s\n\n%s\n' '\nRAM details\n%s\n' %s\ %s '%s\n-\t%s\n' );S0() { echo ' { q=$NF+0;$NF="";u=$(NF-1);$(NF-1)="";gsub(/^ +| +$/,"");if(q>='${p[$1]}') printf("%s (UID %s) is using %s '${p[$2]}'",$0,u,q);} ';};s=(' /^ *$|CSConfigDot/d;s/^ */ /;s/[-0-9A-Fa-f]{22,}/UUID/g;s/(ochat)\.[^.]+(\..+)/\1\2/;/Shared/!s/\/Users\/[^/]+/~/g ' ' s/^ +//;/(de|[nst]):/p;' ' {sub(/^ +/,"")};/r:/;/y:/&&$2<'${p[10]} ' 1s/://;3,6d;/[my].+:/d;s/^ {4}//;H;${ g;s/\n$//;/s: [^EO]|x([^08]|02[^F]|8[^0])/p;} ' ' 5h;6{ H;g;/P/!p;} ' ' ($1~/^Cy/&&$3>'${p[11]}')||($1~/^Cond/&&$2!~/^N/) ' ' /:$/{ N;/:.+:/d;s/ *://;b0'$'\n'' };/^ *(V.+ [0N]|Man).+ /{ s/ 0x.... //;s/[()]//g;s/(.+: )(.+)/ (\2)/;H;};$b0'$'\n'' d;:0'$'\n'' x;s/\n\n//;/Apple[ ,]|Intel|SMSC/d;s/\n.*//;/\)$/p;' ' s/^.*C/C/;H;${ g;/No th|pms/!p;} ' '/= [^GO]/p' '{$1=""};1' ' /Of/!{ s/^.+is |\.//g;p;} ' ' $0&&!/ / { n++;print;} END { if(n<200) print "com.apple.";} ' ' $3~/[0-9]:[0-9]{2}$/ { gsub(/:[0-9:a-f]{14}/,"");} { print|"tail -n'${p[12]}'";} ' ' NR==2&&$4<='${p[13]}' { print $4;} ' ' END { $2/=256;if($2>='${p[15]}') print int($2) } ' ' NR!=13{next};{sub(/[+-]$/,"",$NF)};'"`S0 21 22`" 'NR!=2{next}'"`S0 37 17`" ' NR!=5||$8!~/[RW]/{next};{ $(NF-1)=$1;$NF=int($NF/10000000);for(i=1;i<=3;i++){$i="";$(NF-1-i)="";};};'"`S0 19 20`" 's:^:/:p' '/\.kext\/(Contents\/)?Info\.plist$/p' 's/^.{52}(.+) <.+/\1/p' ' /Launch[AD].+\.plist$/ { n++;print;} END { print "'${p[41]}'";if(n<200) print "/System/";} ' '/\.xpc\/(Contents\/)?Info\.plist$/p' ' NR>1&&!/0x|\.[0-9]+$|com\.apple\.launchctl\.(Aqua|Background|System)$|'${p[41]}'/ { print $3;} ' ' /\.(framew|lproj)|\):/d;/plist:|:.+(Mach|scrip)/s/:[^:]+//p ' '/^root$/p' ' !/\/Contents\/.+\/Contents|Applic|Autom|Frameworks/&&/Lib.+\/Info.plist$/ { n++;print;} END { if(n<1100) print "/System/";} ' '/^\/usr\/lib\/.+dylib$/p' ' /Temp|emac/{next};/(etc|Preferences|Launch[AD].+)\// { sub(".(/private)?","");n++;print;} END { print "'${p[41]}'.plist\t'${p[42]}'";if(n<500) print "Launch";} ' ' /\/(Contents\/.+\/Contents|Frameworks)\/|\.wdgt\/.+\.([bw]|plu)/d;p;' 's/\/(Contents\/)?Info.plist$//;p' ' { gsub("^| |\n","\\|\\|kMDItem'${p[35]}'=");sub("^...."," ") };1 ' p '{print $3"\t"$1}' 's/\'$'\t''.+//p' 's/1/On/p' '/Prox.+: [^0]/p' '$2>'${p[43]}'{$2=$2-1;print}' ' BEGIN { i="'${p[26]}'";M1='${p[16]}';M2='${p[18]}';M3='${p[31]}';M4='${p[32]}';} !/^A/{next};/%/ { getline;if($5<M1) a="user "$2"%, system "$4"%";} /disk0/&&$4>M2 { b=$3" ops/s, "$4" blocks/s";} $2==i { if(c) { d=$3+$4+$5+$6;next;};if($4>M3||$6>M4) c=int($4/1024)" in, "int($6/1024)" out";} END { if(a) print "CPU: "a;if(b) print "I/O: "b;if(c) print "Net: "c" (KiB/s)";if(d) print "Net errors: "d" packets/s";} ' ' /r\[0\] /&&$NF!~/^1(0|72\.(1[6-9]|2[0-9]|3[0-1])|92\.168)\./ { print $NF;exit;} ' ' !/^T/ { printf "(static)";exit;} ' '/apsd|BKAg|OpenD/!s/:.+//p' ' (/k:/&&$3!~/(255\.){3}0/ )||(/v6:/&&$2!~/A/ ) ' ' $1~"lR"&&$2<='${p[25]}';$1~"li"&&$3!~"wpa2";' ' BEGIN { FS=":";p="uniq -c|sed -E '"'s/ +\\([0-9]+\\) \\(.+\\)/\\\2 x\\\1/;s/x1$//'"'";} { n=split($3,a,".");sub(/_2[01].+/,"",$3);print($2,$3,a[n],$1)|p;b=b$1;} END { if(b) print("\n\t* Code injection");} ' ' NR!=4{next} {$NF/=10240} '"`S0 27 14`" ' END { if($3~/[0-9]/)print$3;} ' ' BEGIN { L='${p[36]}';} !/^[[:space:]]*(#.*)?$/ { l++;if(l<=L) f=f"\n "$0;} END { F=FILENAME;if(!F) exit;if(!f) f="\n [N/A]";"file -b "F|getline T;if(T!~/^(AS.+ (En.+ )?text$|POSIX sh.+ text ex)/) F=F" ("T")";printf("\nContents of %s\n%s\n",F,f);if(l>L) printf("\n ...and %s more line(s)\n",l-L);} ' ' /^ +[NP].+ =/h;/^( +D.+[{]|[}])/{ g;s/.+= //p;};' 's/0/Off/p' ' END{print NR} ' ' /id: N|te: Y/{i++} END{print i} ' ' / / { print "'"${p[28]}"'";exit;};1;' '/ en/!s/\.//p' ' NR!=13{next};{sub(/[+-M]$/,"",$NF)};'"`S0 39 40`" ' $10~/\(L/&&$9!~"localhost" { sub(/.+:/,"",$9);print $1": "$9;} ' '/^ +r/s/.+"(.+)".+/\1/p' 's/(.+\.wdgt)\/(Contents\/)?Info\.plist$/\1/p' 's/^.+\/(.+)\.wdgt$/\1/p' ' /l: /{ /DVD/d;s/.+: //;b0'$'\n'' };/s: /{ /V/d;s/^ */- /;H;};$b0'$'\n'' d;:0'$'\n'' x;/APPLE [^:]+$/d;p;' ' /^find: /d;p;' "`S0 44 45`" );c1=(system_profiler pmset\ -g nvram fdesetup find syslog df vm_stat sar ps sudo\ crontab sudo\ iotop top pkgutil 'PlistBuddy 2>&1 -c "Print' whoami cksum kextstat launchctl sudo\ launchctl crontab 'sudo defaults read' stat lsbom mdfind ' for i in ${p[24]};do ${c1[18]} ${c2[27]} $i;done;' defaults\ read scutil sudo\ dtrace sudo\ profiles sed\ -En awk /S*/*/P*/*/*/C*/*/airport networksetup mdutil sudo\ lsof test );c2=(com.apple.loginwindow\ LoginHook '" /L*/P*/loginw*' '" L*/P*/*loginit*' 'L*/Ca*/com.ap*.Saf*/E*/* -d 1 -name In*t -exec '"${c1[14]}"' :CFBundleDisplayName" {} \;|sort|uniq' '~ $TMPDIR.. \( -flags +sappnd,schg,uappnd,uchg -o ! -user $UID -o ! -perm -600 \)' '.??* -path .Trash -prune -o -type d -name *.app -print -prune' :${p[35]}\" :Label\" '{/,}L*/{Con,Pref}* -type f ! -size 0 -name *.plist -exec plutil -s {} \;' "-f'%N: %l' Desktop L*/Keyc*" therm sysload boot-args status " -F '\$Time \$Message' -k Sender kernel -k Message Req 'bad |Beac|caug|dead[^bl]|FAIL|fail|GPU |hfs: Ru|inval|jnl:|last value [1-9]|n Cause: -|NVDA\(|pagin|proc: t|Roamed|rror|ssert|Thrott|tim(ed? ?|ing )o|WARN' -k Message Rne 'Goog|ksadm|SMC:' -o -k Sender fseventsd -k Message Req 'SL' " '-du -n DEV -n EDEV 1 10' 'acrx -o comm,ruid,%cpu' '-t1 10 1' '-f -pfc /var/db/r*/com.apple.*.{BS,Bas,Es,J,OSXU,Rem,up}*.bom' '{/,}L*/Lo*/Diag* -type f -regex .\*[cgh] ! -name *ag \( -exec grep -lq "^Thread c" {} \; -exec printf \* \; -o -true \) -execdir stat -f:%Sc:%N -t%F {} \;|sort -t: -k2 |tail -n'${p[38]} '-L {/{S*/,},}L*/Lau* -type f' '-L /{S*/,}L*/StartupItems -type f -exec file {} +' '-L /S*/L*/{C*/Sec*A,E}* {/,}L*/{A*d,Ca*/*/Ex,Compon,Ex,Inter,iTu,Keyb,Mail/B,Pr*P,Qu*T,Scripti,Sec,Servi,Spo,Widg}* -type f -name Info.plist' '/usr/lib -type f -name *.dylib' `awk "${s[31]}"<<<${p[23]}` "/e*/{auto,{cron,fs}tab,hosts,{[lp],sy}*.conf,pam.d/*,ssh{,d}_config,*.local} {,/usr/local}/etc/periodic/*/* /L*/P*{,/*}/com.a*.{Bo,sec*.ap}*t /S*/L*/Lau*/*t .launchd.conf" list getenv /Library/Preferences/com.apple.alf\ globalstate --proxy '-n get default' -I --dns -getdnsservers\ "${p[N5]}" -getinfo\ "${p[N5]}" -P -m\ / '' -n1 '-R -l1 -n1 -o prt -stats command,uid,prt' '--regexp --only-files --files com.apple.pkg.*|sort|uniq' -kl -l -s\ / '-R -l1 -n1 -o mem -stats command,uid,mem' '+c0 -i4TCP:0-1023' com.apple.dashboard\ layer-gadgets '-d /L*/Mana*/$USER&&echo On' '-app Safari WebKitDNSPrefetchingEnabled' "+c0 -l|awk '{print(\$1,\$3)}'|sort|uniq -c|sort -n|tail -1|awk '{print(\$2,\$3,\$1)}'" );N1=${#c2[@]};for j in {0..9};do c2[N1+j]=SP${p[j]}DataType;done;N2=${#c2[@]};for j in 0 1;do c2[N2+j]="-n ' syscall::'${p[33+j]}':return { @out[execname,uid]=sum(arg0) } tick-10sec { trunc(@out,1);exit(0);} '";done;l=(Restricted\ files Hidden\ apps 'Elapsed time (s)' POST Battery Safari\ extensions Bad\ plists 'High file counts' User Heat System\ load boot\ args FileVault Diagnostic\ reports Log 'Free space (MiB)' 'Swap (MiB)' Activity 'CPU per process' Login\ hook 'I/O per process' Mach\ ports kexts Daemons Agents launchd Startup\ items Admin\ access Root\ access Bundles dylibs Apps Font\ issues Inserted\ dylibs Firewall Proxies DNS TCP/IP Wi-Fi Profiles Root\ crontab User\ crontab 'Global login items' 'User login items' Spotlight Memory Listeners Widgets Parental\ Controls Prefetching SATA Descriptors );N3=${#l[@]};for i in 0 1 2;do l[N3+i]=${p[5+i]};done;N4=${#l[@]};for j in 0 1;do l[N4+j]="Current ${p[29+j]}stream data";done;A0() { id -G|grep -qw 80;v[1]=$?;((v[1]==0))&&sudo true;v[2]=$?;v[3]=`date +%s`;clear >&-;date '+Start time: %T %D%n';};for i in 0 1;do eval ' A'$((1+i))'() { v=` eval "${c1[$1]} ${c2[$2]}"|'${c1[30+i]}' "${s[$3]}" `;[[ "$v" ]];};A'$((3+i))'() { v=` while read i;do [[ "$i" ]]&&eval "${c1[$1]} ${c2[$2]}" \"$i\"|'${c1[30+i]}' "${s[$3]}";done<<<"${v[$4]}" `;[[ "$v" ]];};A'$((5+i))'() { v=` while read i;do '${c1[30+i]}' "${s[$1]}" "$i";done<<<"${v[$2]}" `;[[ "$v" ]];};';done;A7(){ v=$((`date +%s`-v[3]));};B2(){ v[$1]="$v";};for i in 0 1;do eval ' B'$i'() { v=;((v['$((i+1))']==0))||{ v=No;false;};};B'$((3+i))'() { v[$2]=`'${c1[30+i]}' "${s[$3]}"<<<"${v[$1]}"`;} ';done;B5(){ v[$1]="${v[$1]}"$'\n'"${v[$2]}";};B6() { v=` paste -d: <(printf "${v[$1]}") <(printf "${v[$2]}")|awk -F: ' {printf("'"${f[$3]}"'",$1,$2)} ' `;};B7(){ v=`grep -Fv "${v[$1]}"<<<"$v"`;};C0(){ [[ "$v" ]]&&echo "$v";};C1() { [[ "$v" ]]&&printf "${f[$1]}" "${l[$2]}" "$v";};C2() { v=`echo $v`;[[ "$v" != 0 ]]&&C1 0 $1;};C3() { v=`sed -E "$s"<<<"$v"`&&C1 1 $1;};for i in 1 2;do for j in 0 2 3;do eval D$i$j'(){ A'$i' $1 $2 $3; C'$j' $4;};';done;done;{ A0;D20 0 $((N1+1)) 2;D10 0 $N1 1;B0;C2 27;B0&&! B1&&C2 28;D12 15 37 25 8;A1 0 $((N1+2)) 3;C0;D13 0 $((N1+3)) 4 3;D23 0 $((N1+4)) 5 4;D13 0 $((N1+9)) 59 50;for i in 0 1 2;do D13 0 $((N1+5+i)) 6 $((N3+i));done;D13 1 10 7 9;D13 1 11 8 10;D22 2 12 9 11;D12 3 13 10 12;D23 4 19 44 13;D23 5 14 12 14;D22 6 36 13 15;D22 7 37 14 16;D23 8 15 38 17;D22 9 16 16 18;B1&&{ D22 35 49 61 51;D22 11 17 17 20;for i in 0 1;do D22 28 $((N2+i)) 45 $((N4+i));done;};D22 12 44 54 45;D22 12 39 15 21;A1 13 40 18;B2 4;B3 4 0 19;A3 14 6 32 0;B4 0 5 11;A1 17 41 20;B7 5;C3 22;B4 4 6 21;A3 14 7 32 6;B4 0 7 11;B3 4 0 22;A3 14 6 32 0;B4 0 8 11;B5 7 8;B1&&{ A2 19 26 23;B7 7;C3 23;};A2 18 26 23;B7 7;C3 24;A2 4 20 21;B7 6;B2 9;A4 14 7 52 9;B2 10;B6 9 10 4;C3 25;D13 4 21 24 26;B4 4 12 26;B3 4 13 27;A1 4 22 29;B7 12;B2 14;A4 14 6 52 14;B2 15;B6 14 15 4;B3 0 0 30;C3 29;A1 4 23 27;B7 13;C3 30;D13 24 24 32 31;D13 25 37 32 33;A2 23 18 28;B2 16;A2 16 25 33;B7 16;B3 0 0 34;B2 21;A6 47 21&&C0;B1&&{ D13 21 0 32 19;D13 10 42 32 40;D22 29 35 46 39;};D13 14 1 48 42;D12 34 43 53 44;D22 0 $((N1+8)) 51 32;D13 4 8 41 6;D12 26 28 35 34;D13 27 29 36 35;A2 27 32 39&&{ B2 19;A2 33 33 40;B2 20;B6 19 20 3;};C2 36;D23 33 34 42 37;B1&&D23 35 45 55 46;D23 32 31 43 38;D12 36 47 32 48;D13 20 42 32 41;D13 14 2 48 43;D13 4 5 32 1;D13 4 3 60 5;D12 26 48 49 49;B3 4 22 57;A1 26 46 56;B7 22;B3 0 0 58;C3 47;D22 4 4 50 0;D23 22 9 37 7;A7;C2 2;} 2>/dev/null|pbcopy;exit 2>&-
Copy the selected text to the Clipboard by pressing the key combination command-C.
8. Launch the built-in Terminal application in any of the following ways:
☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
☞ Open LaunchPad. Click Utilities, then Terminal in the icon grid.
Click anywhere in the Terminal window and paste by pressing command-V. The text you pasted should vanish immediately. If it doesn't, press the return key.
9. If you see an error message in the Terminal window such as "Syntax error" or "Event not found," enter
exec bash
and press return. Then paste the script again.
10. If you're logged in as an administrator, you'll be prompted for your login password. Nothing will be displayed when you type it. You will not see the usual dots in place of typed characters. Make sure caps lock is off. Type carefully and then press return. You may get a one-time warning to be careful. If you make three failed attempts to enter the password, the test will run anyway, but it will produce less information. In most cases, the difference is not important. If you don't know the password, or if you prefer not to enter it, press the key combination control-C or just press return three times at the password prompt. Again, the script will still run.
If you're not logged in as an administrator, you won't be prompted for a password. The test will still run. It just won't do anything that requires administrator privileges.
11. The test may take a few minutes to run, depending on how many files you have and the speed of the computer. A computer that's abnormally slow may take longer to run the test. While it's running, there will be nothing in the Terminal window and no indication of progress. Wait for the line
[Process completed]
to appear. If you don't see it within half an hour or so, the test probably won't complete in a reasonable time. In that case, close the Terminal window and report the results. No harm will be done.
12. When the test is complete, quit Terminal. The results will have been copied to the Clipboard automatically. They are not shown in the Terminal window. Please don't copy anything from there. All you have to do is start a reply to this comment and then paste by pressing command-V again.
At the top of the results, there will be a line that begins with the words "Start Time." If you don't see that, but instead see a mass of gibberish, you didn't wait for the "Process completed" message to appear in the Terminal window. Please wait for it and try again.
If any private information, such as your name or email address, appears in the results, anonymize it before posting. Usually that won't be necessary.
13. When you post the results, you might see an error message on the web page: "You have included content in your post that is not permitted," or "You are not authorized to post." That's a bug in the forum software. Please post the test results on Pastebin, then post a link here to the page you created.
14. This is a public forum, and others may give you advice based on the results of the test. They speak only for themselves, and I don't necessarily agree with them.
Copyright © 2014 by Linc Davis. As the sole author of this work, I reserve all rights to it except as provided in the Use Agreement for the Apple Support Communities website ("ASC"). Readers of ASC may copy it for their own personal use. Neither the whole nor any part may be redistributed. -
Fwd'ing to security newsgroup
-------- Original Message --------
Subject: Client accessing MBeanHome for more than one domain receives
SecurityException
Date: 4 Mar 2004 07:27:33 -0800
From: Dinesh Bhat <[email protected]>
Reply-To: Dinesh Bhat <[email protected]>
Organization: BEA NEWS SITE
Newsgroups: weblogic.developer.interest.management
Hi,
When a client accesses MBeans of more than one domains (Weblogic 8.1)
that have
different passwords, it receives a SecurityException. This occurs when
the MBeanHome
for each domain is looked up at initialization and reused for each
request ( to
access MBeans ). The security exception does not occur if the MBeanHome
for each
domain is looked up for each request. On initial review, this behavoir
seems inconsistent.
Looking up the MBeanHome for each request may introduce a significant
overhead.
I am not sure if concurrent lookups would also cause the same problem.
I have read on another post that we can work around this problem by
establishing
a trust relationship between the servers, but this may not be feasible
when one
is monitoring a lot of servers and the overhead of configuration may be
an issue.
I have attached code that can reproduce the problem.
Please advise on the correct approach.
Thanks
Dinesh Bhat
Panacya Inc.
import java.util.ArrayList;
import java.util.Set;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Hashtable;
import javax.management.MBeanServer;
import javax.naming.Context;
import weblogic.jndi.Environment;
import weblogic.management.MBeanHome;
* This class reproduces the Security Exception that is caused when a client tries to access
* MBeans of more than one domain with different weblogic passwords. Here is the stacktrace of the
* exception
* java.lang.SecurityException: [Security:090398]Invalid Subject: principals=[weblogic, Administrators]
at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:108)
at weblogic.rmi.internal.BasicRemoteRef.invoke(BasicRemoteRef.java:138)
at weblogic.management.internal.AdminMBeanHomeImpl_811_WLStub.getDomainName(Unknown Source)
at WLSecurityTest.getWeblogicInfo(WLSecurityTest.java:140)
at WLSecurityTest.runTest(WLSecurityTest.java:75)
at WLSecurityTest.<init>(WLSecurityTest.java:66)
at WLSecurityTest.main(WLSecurityTest.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at com.intellij.rt.execution.application.AppMain.main(Unknown Source)
Caused by: java.lang.SecurityException: [Security:090398]Invalid Subject: principals=[weblogic, Administrators]
at weblogic.security.service.SecurityServiceManager.seal(SecurityServiceManager.java:682)
at weblogic.rjvm.MsgAbbrevInputStream.getSubject(MsgAbbrevInputStream.java:181)
at weblogic.rmi.internal.BasicServerRef.acceptRequest(BasicServerRef.java:814)
at weblogic.rmi.internal.BasicServerRef.dispatch(BasicServerRef.java:299)
at weblogic.rjvm.RJVMImpl.dispatchRequest(RJVMImpl.java:920)
at weblogic.rjvm.RJVMImpl.dispatch(RJVMImpl.java:841)
at weblogic.rjvm.ConnectionManagerServer.handleRJVM(ConnectionManagerServer.java:222)
at weblogic.rjvm.ConnectionManager.dispatch(ConnectionManager.java:794)
at weblogic.rjvm.t3.T3JVMConnection.dispatch(T3JVMConnection.java:570)
at weblogic.socket.NTSocketMuxer.processSockets(NTSocketMuxer.java:105)
at weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:32)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
* Note: the exception is caused only when the MBeanHome for each domain is cached and used for subsequent
* transactions. The exception does not occur if the MBeanHome for each domain is looked up for each transaction. This
* would significant overhead in practice. Also the transactions across the various domains occurs serially, hence
* the effect of concurrent lookups has to be tested.
* Usage:
* This class has been tested with weblogic 8.1
* The class needs weblogic.jar in its classpath
* One can specify the weblogic details as System properties. The properties need to be specified in
* the following format:
* wls.host.n, wls.userId.n, wls.password.n where n is the weblogix instance number. Also specify
* the boolean system property reconnect.each.iteration to toggle between reconnecting or not reconnecting
* for each iteration. When not reconnecting for each iteration, the MBeanHome is reused and the Security Exception
* occurs.
* Following is the example of system properties
* -Dwls.host.0=localhost:7001 -Dwls.userId.0=weblogic -Dwls.password.0=weblogic
* -Dwls.host.1=localhost:7011 -Dwls.userId.1=weblogic -Dwls.password.1=weblogic1
* -Dwls.host.2=localhost:7021 -Dwls.userId.2=weblogic -Dwls.password.2=weblogic2
* -Dreconnect.each.iteration=false
public class WLSecurityTest
ArrayList wlsDetailsList = new ArrayList();
HashMap connectionMap = new HashMap();
public static void main(String[] args)
try
WLSecurityTest wlSecurityTest = new WLSecurityTest();
catch (Exception e)
e.printStackTrace();
* Constructor
* @throws Exception
public WLSecurityTest() throws Exception
int noOfTries = 10;
getWLSDetails();
for( int i=0; i <= noOfTries; i++)
runTest();
* Runs the test
private void runTest()
for (int i = 0; i < wlsDetailsList.size(); i++)
WLSDetails wlsDetails = (WLSDetails) wlsDetailsList.get(i);
getWeblogicInfo(wlsDetails);
* Get Weblogic details from System properties
* @throws Exception
private void getWLSDetails() throws Exception
wlsDetailsList = new ArrayList();
String hostKeyTmpl = "wls.host";
String userIdKeyTmpl = "wls.userId";
String passwordKeyTmpl = "wls.password";
boolean done = false;
for (int i = 0; !done; i++)
WLSDetails wlsDetails = new WLSDetails();
String hostKey = hostKeyTmpl + "." + Integer.toString(i);
String userIdKey = userIdKeyTmpl + "." + Integer.toString(i);
String passwordKey = passwordKeyTmpl + "." + Integer.toString(i);
wlsDetails.hostName = System.getProperty(hostKey);
done = (wlsDetails.hostName == null) || (wlsDetails.hostName.length() == 0);
if (!done)
wlsDetails.userId = System.getProperty(userIdKey);
wlsDetails.password = System.getProperty(passwordKey);
connect(wlsDetails);
wlsDetailsList.add(wlsDetails);
* Lookup the MBeanHome for the specified weblogic server
* @param wlsDetails
* @throws Exception
public synchronized void connect(WLSecurityTest.WLSDetails wlsDetails) throws Exception
Context ctx = null;
MBeanHome mbHomeLocal = null;
try
Environment env = new Environment();
env.setProviderUrl("t3://" + wlsDetails.hostName);
env.setSecurityPrincipal(wlsDetails.userId);
env.setSecurityCredentials(wlsDetails.password);
Hashtable hashtable = env.getProperties();
System.out.println(hashtable.toString());
ctx = env.getInitialContext();
wlsDetails._mBeanHome = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);
catch (Exception e)
e.printStackTrace();
* Gets weblogic information using MBeans
* @param wlsDetails
public synchronized void getWeblogicInfo(WLSDetails wlsDetails)
try
boolean reconnectEachIteration =
Boolean.getBoolean("reconnect.each.iteration");
if( (reconnectEachIteration) || ((wlsDetails._mBeanHome == null) && (!reconnectEachIteration) ))
connect(wlsDetails);
MBeanHome mbHomeLocal = wlsDetails._mBeanHome;
String domainName = mbHomeLocal.getDomainName();
Set allMBeans = mbHomeLocal.getAllMBeans();
System.out.println("Size: " + allMBeans.size());
Set clusterMBeans = mbHomeLocal.getMBeansByType("Cluster", domainName);
System.out.println(clusterMBeans);
MBeanServer mBeanServer = mbHomeLocal.getMBeanServer();
catch (Exception ex)
ex.printStackTrace();
* Class that holds weblogic server details
class WLSDetails
String hostName = "";
String userId = "";
String password = "";
MBeanHome _mBeanHome = null;If Server version is 61.
Make user "system" password of all weblogic servers same.
If Server version above 61(70,81)
In the Security Advanced Settings un check generated credential and specify a common credentail for all the weblogic servers(domains).
Maybe you are looking for
-
Hi, I am using SSRS 2008 R2. I have two TABLIX in a report. One is TABLIX with row/clumn grouping. 2nd one is flat view. Here each tablix is dispaly it's data on single page for each. My Requirement on First TABLIX is: 1. I have to make column
-
"UNMOUNTABLE_BOOT_VOLUME" Here's what fixed my problem
I have been unable to load winXP on a new system. (MSI KT3 ultra, AMD XP 2000+, 512mb crucial DDR, WD 80GB, MSI GF2mx-400, Antec 300watt PS) The system would boot to the XP cd fine, it would format the HD without problems, however, upon rebooting, th
-
Online printing services and that built into Aperture
Hi, I regularly have pictures printed by a well known high street photo store here in the UK but just recently I've been disappointed with some of the results. They're coming back too dark and with a yellow cast even though the original files look fi
-
Hi Folks, I am not able to perform multiple personal actions on the same day. I have checked the entries in table T529A ,where the column U0302 is checked for all personla actions . Further i checked table T77S0 where the switch is activated for ADM
-
Hi, I am using BAPI to create Purchase Order. But it is showing error as 'Check item number 0 in table POSCHEDULEX ' Could u pls someone help me to get rid of this problem constants : c_x value 'X'. data: del_date type sy-datum. data: pohead t