Search Results

Search found 13006 results on 521 pages for 'exception'.

Page 15/521 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Android Uncaught Exception

    - by Agrim Asthana
    09-30 02:32:31.474: D/ddm-heap(214): Got feature list request 09-30 02:32:31.634: D/AndroidRuntime(214): Shutting down VM 09-30 02:32:31.634: W/dalvikvm(214): threadid=3: thread exiting with uncaught exception (group=0x4001b188) 09-30 02:32:31.634: E/AndroidRuntime(214): Uncaught handler: thread main exiting due to uncaught exception 09-30 02:32:31.654: E/AndroidRuntime(214): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mjcet.mjcet/com.mjcet.mjcet.MJCET}: java.lang.ClassNotFoundException: com.mjcet.mjcet.MJCET in loader dalvik.system.PathClassLoader@44e8c820 09-30 02:32:31.654: E/AndroidRuntime(214): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417) 09-30 02:32:31.654: E/AndroidRuntime(214): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 09-30 02:32:31.654: E/AndroidRuntime(214): at android.app.ActivityThread.access$2200(ActivityThread.java:119) 09-30 02:32:31.654: E/AndroidRuntime(214): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 09-30 02:32:31.654: E/AndroidRuntime(214): at android.os.Handler.dispatchMessage(Handler.java:99) 09-30 02:32:31.654: E/AndroidRuntime(214): at android.os.Looper.loop(Looper.java:123) 09-30 02:32:31.654: E/AndroidRuntime(214): at android.app.ActivityThread.main(ActivityThread.java:4363) 09-30 02:32:31.654: E/AndroidRuntime(214): at java.lang.reflect.Method.invokeNative(Native Method) 09-30 02:32:31.654: E/AndroidRuntime(214): at java.lang.reflect.Method.invoke(Method.java:521) 09-30 02:32:31.654: E/AndroidRuntime(214): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 09-30 02:32:31.654: E/AndroidRuntime(214): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 09-30 02:32:31.654: E/AndroidRuntime(214): at dalvik.system.NativeStart.main(Native Method) 09-30 02:32:31.654: E/AndroidRuntime(214): Caused by: java.lang.ClassNotFoundException: com.mjcet.mjcet.MJCET in loader dalvik.system.PathClassLoader@44e8c820 09-30 02:32:31.654: E/AndroidRuntime(214): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243) 09-30 02:32:31.654: E/AndroidRuntime(214): at java.lang.ClassLoader.loadClass(ClassLoader.java:573) 09-30 02:32:31.654: E/AndroidRuntime(214): at java.lang.ClassLoader.loadClass(ClassLoader.java:532) 09-30 02:32:31.654: E/AndroidRuntime(214): at android.app.Instrumentation.newActivity(Instrumentation.java:1021) 09-30 02:32:31.654: E/AndroidRuntime(214): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409) 09-30 02:32:31.654: E/AndroidRuntime(214): ... 11 more 09-30 02:32:31.684: I/dalvikvm(214): threadid=7: reacting to signal 3 09-30 02:32:31.684: E/dalvikvm(214): Unable to open stack trace file '/data/anr/traces.txt': Permission denied the above is my debugging output for the below activities LOGINACTIVITY.java package com.agrim.mjcet; import com.agrim.mjcet.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; //import android.widget.TextView; import android.widget.Button; import android.widget.EditText; import android.view.View.OnClickListener; public class LoginActivity extends Activity { EditText txtUserName; EditText txtPassword; Button btnLogin; Button btnCancel; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setting default screen to login.xml setContentView(R.layout.main); txtUserName=(EditText)this.findViewById(R.id.txtUname); txtPassword=(EditText)this.findViewById(R.id.txtPwd); btnLogin=(Button)this.findViewById(R.id.btnLogin); btnLogin=(Button)this.findViewById(R.id.btnLogin); btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Switching to Register screen if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())) { Intent myIntent = new Intent(getApplicationContext(),SampleActivity.class); startActivityForResult(myIntent, 0); } } } ); } } SAMPLE ACTIVITY.java package com.agrim.mjcet; import com.agrim.mjcet.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class SampleActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set View to register.xml setContentView(R.layout.lol); TextView HomeScreen = (TextView) findViewById(R.id.back); HomeScreen.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { // Closing registration screen // Switching to Login Screen/closing register screen finish(); } }); } } and here are my 2 layouts MAIN.XML <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#000000" android:stretchColumns="1"> <TableRow> <TextView android:text="@string/user_name" android:textColor="#347235" android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_marginLeft="25dip" android:layout_height="wrap_content"> </TextView> <EditText android:text="" android:inputType="text" android:id="@+id/txtUname" android:layout_weight="0.75" android:layout_width="wrap_content" android:layout_marginRight="10dip" android:layout_marginBottom="5dip" android:background="#FFFFFF" android:layout_height="wrap_content"> </EditText> </TableRow> <TableRow> <TextView android:text="@string/password" android:textColor="#347235" android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="25dip"> </TextView> <EditText android:text="" android:inputType="textPassword" android:id="@+id/txtPwd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="10dip" android:layout_weight="1" android:background="#FFFFFF" android:gravity="center"> </EditText> </TableRow> <TableRow> <Button android:id="@+id/btnLogin" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#FFFFFF" android:layout_marginTop="25dip" android:layout_marginLeft="50dip" android:onClick="onClickMyButton" android:text="@string/login" /> <Button android:id="@+id/btnCancel" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#FFFFFF" android:layout_marginTop="25dip" android:layout_marginLeft="100dip" android:layout_marginRight="50dip" android:text="@string/cancel" /> </TableRow> <FrameLayout android:layout_width="wrap_content" android:layout_height="match_parent" > <ImageView android:layout_width="fill_parent" android:layout_height="match_parent" android:scaleType="centerInside" android:src="@drawable/logo_invert" android:contentDescription="@drawable/logo_invert"/> </FrameLayout> </TableLayout> and finally LOL.xml <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:background="#000000" android:layout_height="fill_parent" > <ImageView android:layout_width="fill_parent" android:id="@+id/back" android:layout_height="match_parent" android:scaleType="centerInside" android:src="@drawable/lol" android:contentDescription="@drawable/lol"> </ImageView> <RelativeLayout android:layout_width="match_parent" android:layout_height="138dp" android:orientation="vertical" android:gravity="bottom" > <TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="@string/coming_soon" android:textColor="#347235" /> </RelativeLayout> </FrameLayout> I get a force close upon initialization.. and yes this is my first android app :)

    Read the article

  • getting Null pointer exception

    - by Abhijeet
    Hi I am getting this message on emulator when I run my android project: The application MediaPlayerDemo_Video.java (process com.android.MediaPlayerDemo_Video) has stopped unexpectedly. Please try again I am trying to run the MediaPlayerDemo_Video.java given in ApiDemos in the Samples given on developer.android.com. The code is : package com.android.MediaPlayerDemo_Video; import android.app.Activity; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnBufferingUpdateListener; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnPreparedListener; import android.media.MediaPlayer.OnVideoSizeChangedListener; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; public class MediaPlayerDemo_Video extends Activity implements OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback { private static final String TAG = "MediaPlayerDemo"; private int mVideoWidth; private int mVideoHeight; private MediaPlayer mMediaPlayer; private SurfaceView mPreview; private SurfaceHolder holder; private String path; private Bundle extras; private static final String MEDIA = "media"; // private static final int LOCAL_AUDIO = 1; // private static final int STREAM_AUDIO = 2; // private static final int RESOURCES_AUDIO = 3; private static final int LOCAL_VIDEO = 4; private static final int STREAM_VIDEO = 5; private boolean mIsVideoSizeKnown = false; private boolean mIsVideoReadyToBePlayed = false; /** * * Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.mediaplayer_2); mPreview = (SurfaceView) findViewById(R.id.surface); holder = mPreview.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); extras = getIntent().getExtras(); } private void playVideo(Integer Media) { doCleanUp(); try { switch (Media) { case LOCAL_VIDEO: // Set the path variable to a local media file path. path = ""; if (path == "") { // Tell the user to provide a media file URL. Toast .makeText( MediaPlayerDemo_Video.this, "Please edit MediaPlayerDemo_Video Activity, " + "and set the path variable to your media file path." + " Your media file must be stored on sdcard.", Toast.LENGTH_LONG).show(); } break; case STREAM_VIDEO: /* * Set path variable to progressive streamable mp4 or * 3gpp format URL. Http protocol should be used. * Mediaplayer can only play "progressive streamable * contents" which basically means: 1. the movie atom has to * precede all the media data atoms. 2. The clip has to be * reasonably interleaved. * */ path = ""; if (path == "") { // Tell the user to provide a media file URL. Toast .makeText( MediaPlayerDemo_Video.this, "Please edit MediaPlayerDemo_Video Activity," + " and set the path variable to your media file URL.", Toast.LENGTH_LONG).show(); } break; } // Create a new media player and set the listeners mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(path); mMediaPlayer.setDisplay(holder); mMediaPlayer.prepare(); mMediaPlayer.setOnBufferingUpdateListener(this); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnVideoSizeChangedListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); } catch (Exception e) { Log.e(TAG, "error: " + e.getMessage(), e); } } public void onBufferingUpdate(MediaPlayer arg0, int percent) { Log.d(TAG, "onBufferingUpdate percent:" + percent); } public void onCompletion(MediaPlayer arg0) { Log.d(TAG, "onCompletion called"); } public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { Log.v(TAG, "onVideoSizeChanged called"); if (width == 0 || height == 0) { Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")"); return; } mIsVideoSizeKnown = true; mVideoWidth = width; mVideoHeight = height; if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) { startVideoPlayback(); } } public void onPrepared(MediaPlayer mediaplayer) { Log.d(TAG, "onPrepared called"); mIsVideoReadyToBePlayed = true; if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) { startVideoPlayback(); } } public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) { Log.d(TAG, "surfaceChanged called"); } public void surfaceDestroyed(SurfaceHolder surfaceholder) { Log.d(TAG, "surfaceDestroyed called"); } public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "surfaceCreated called"); playVideo(extras.getInt(MEDIA)); } @Override protected void onPause() { super.onPause(); releaseMediaPlayer(); doCleanUp(); } @Override protected void onDestroy() { super.onDestroy(); releaseMediaPlayer(); doCleanUp(); } private void releaseMediaPlayer() { if (mMediaPlayer != null) { mMediaPlayer.release(); mMediaPlayer = null; } } private void doCleanUp() { mVideoWidth = 0; mVideoHeight = 0; mIsVideoReadyToBePlayed = false; mIsVideoSizeKnown = false; } private void startVideoPlayback() { Log.v(TAG, "startVideoPlayback"); holder.setFixedSize(mVideoWidth, mVideoHeight); mMediaPlayer.start(); } } I think the above message is due to Null pointer exception , however I may be false. I am unable to find where the error is . So , Please someone help me out .

    Read the article

  • Windows Azure : Storage Client Exception Unhandled

    - by veda
    I am writing a code for upload large files into the blobs using blocks... When I tested it, it gave me an StorageClientException It stated: One of the request inputs is out of range. I got this exception in this line of the code: blob.PutBlock(block, ms, null); Here is my code: protected void ButUploadBlocks_click(object sender, EventArgs e) { // store upladed file as a blob storage if (uplFileUpload.HasFile) { name = uplFileUpload.FileName; byte[] byteArray = uplFileUpload.FileBytes; Int64 contentLength = byteArray.Length; int numBytesPerBlock = 250 *1024; // 250KB per block int blocksCount = (int)Math.Ceiling((double)contentLength / numBytesPerBlock); // number of blocks MemoryStream ms ; List<string>BlockIds = new List<string>(); string block; int offset = 0; // get refernce to the cloud blob container CloudBlobContainer blobContainer = cloudBlobClient.GetContainerReference("documents"); // set the name for the uploading files string UploadDocName = name; // get the blob reference and set the metadata properties CloudBlockBlob blob = blobContainer.GetBlockBlobReference(UploadDocName); blob.Properties.ContentType = uplFileUpload.PostedFile.ContentType; for (int i = 0; i < blocksCount; i++, offset = offset + numBytesPerBlock) { block = Convert.ToBase64String(BitConverter.GetBytes(i)); ms = new MemoryStream(); ms.Write(byteArray, offset, numBytesPerBlock); blob.PutBlock(block, ms, null); BlockIds.Add(block); } blob.PutBlockList(BlockIds); blob.Metadata["FILETYPE"] = "text"; } } Can anyone tell me how to solve it...

    Read the article

  • Delphi Exception Handling - How to clean up properly?

    - by Tom
    I'm looking at some code in an application of ours and came across something a little odd from what I normally do. With exception handling and cleanup, we (as well as many other programmers out there, I'm sure) use a Try/Finally block embedded with a Try/Except block. Now I'm used to the Try/Except inside the Try/Finally like so: Try Try CouldCauseError(X); Except HandleError; end; Finally FreeAndNil(x); end; but this other block of code is reversed as so: Try Try CouldCauseError(X); Finally FreeAndNil(x); end; Except HandleError; end; Looking around the web, I'm seeing folks doing this both ways, with no explanation as to why. My question is, does it matter which gets the outside block and which gets the inside block? Or will the except and finally sections get handled no matter which way it is structured? Thanks.

    Read the article

  • how to rethrow same exception in sql server

    - by Shantanu Gupta
    I want to rethrow same exception in sql server that has been occured in my try block. I am able to throw same message but i want to throw same error. BEGIN TRANSACTION BEGIN TRY INSERT INTO Tags.tblDomain (DomainName, SubDomainId, DomainCode, Description) VALUES(@DomainName, @SubDomainId, @DomainCode, @Description) COMMIT TRANSACTION END TRY BEGIN CATCH declare @severity int; declare @state int; select @severity=error_severity(), @state=error_state(); RAISERROR(@@Error,@ErrorSeverity,@state); ROLLBACK TRANSACTION END CATCH RAISERROR(@@Error, @ErrorSeverity, @state); This line will show error, but i want functionality something like that. This raises error with error number 50000, but i want erron number to be thrown that i am passing @@error, I want to capture this error no at frontend i.e. catch (SqlException ex) { if ex.number==2627 MessageBox.show("Duplicate value cannot be inserted"); } I want this functionality. which can't be achieved using raiseerror. I dont want to give custom error message at back end.

    Read the article

  • Java Runtime Exception

    - by ikurtz
    when i run my application i get the following error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at javax.swing.text.FlowView$FlowStrategy.layoutRow(FlowView.java:546) at javax.swing.text.FlowView$FlowStrategy.layout(FlowView.java:460) at javax.swing.text.FlowView.layout(FlowView.java:184) at javax.swing.text.BoxView.setSize(BoxView.java:380) at javax.swing.text.BoxView.updateChildSizes(BoxView.java:349) at javax.swing.text.BoxView.setSpanOnAxis(BoxView.java:331) at javax.swing.text.BoxView.layout(BoxView.java:691) at javax.swing.text.BoxView.setSize(BoxView.java:380) at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(BasicTextUI.java:1702) at javax.swing.plaf.basic.BasicTextUI.modelToView(BasicTextUI.java:1034) at javax.swing.text.DefaultCaret.repaintNewCaret(DefaultCaret.java:1291) at javax.swing.text.DefaultCaret$1.run(DefaultCaret.java:1270) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) at java.awt.EventQueue.dispatchEvent(EventQueue.java:597) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) as the error does not mention any of my classes, how would i go about in finding what is causing this? if i try: public void notifyChatMessage(String message){...} the error goes away. but if i try: public void notifyChatMessage(Object message){...} the error is reported. please advise.

    Read the article

  • I am getting a Radix out of range exception on performing decryption

    - by user3672391
    I am generating a keypair and converting one of the same into string which later is inserted into the database using the following code: KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair generatedKeyPair = keyGen.genKeyPair(); PublicKey pubkey = generatedKeyPair.getPublic(); PrivateKey prvkey = generatedKeyPair.getPrivate(); System.out.println("My Public Key>>>>>>>>>>>"+pubkey); System.out.println("My Private Key>>>>>>>>>>>"+prvkey); String keyAsString = new BigInteger(prvkey.getEncoded()).toString(64); I then retrieve the string from the database and convert it back to the original key using the following code (where rst is my ResultSet): String keyAsString = rst.getString("privateKey").toString(); byte[] bytes = new BigInteger(keyAsString, 64).toByteArray(); //byte k[] = "HignDlPs".getBytes(); PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(bytes); KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA"); PrivateKey privKey = rsaKeyFac.generatePrivate(encodedKeySpec); On using the privKey for RSA decryption, I get the following exception java.lang.NumberFormatException: Radix out of range at java.math.BigInteger.<init>(BigInteger.java:294) at com.util.SimpleFTPClient.downloadFile(SimpleFTPClient.java:176) at com.Action.FileDownload.processRequest(FileDownload.java:64) at com.Action.FileDownload.doGet(FileDownload.java:94) Please guide.

    Read the article

  • Unhandled Exception with c++ app on Visual Studio 2008 release build - occurs when returning from fu

    - by Rich
    Hi, I have a (rather large) application that I have written in C++ and until recently it has been running fine outside of visual studio from the release build. However, now, whenever I run it it says "Unhandled exception at 0x77cf205b in myprog.exe: 0xC0000005: Access violation writing location 0x45000200.", and leads me to "crtexe.c" at line 582 ("mainret = main(argc, argv, envp);") if I attempt to debug it. Note that this problem never shows if I run my debug executable outside of visual studio, or if I run my debug or release build within visual studio. It only happens when running the release build outside of visual studio. I have been through and put plenty of printfs and a couple of while(1)s in it to see when it actually crashed, and found that the access violation occurs at exactly the point that the value is returned from the function (I'm returning a pointer to an object). I don't fully understand why I would get an access violation at the point it returns, and it doesn't seem to matter what I'm returning as it still occurs when I return 0. The point it started crashing was when I added a function which does a lot of reading from a file using ifstream. I am opening the stream every time I attempt to read a new file and close it when I finish reading it. If I keep attempting to run it, it will run once in about 20 tries. It seems a lot more reliable if I run it off my pen drive (it seems to crash the first 3 or 4 times then run fine after that - maybe it's due to its slower read speed). Thanks for your help, and if I've missed anything let me know.

    Read the article

  • Xaml parse exception is thrown when i define a duplex contract

    - by Yaroslav
    Hi! I've got a WPF application containing a WCF service. The Xaml code is pretty simple: Enter your text here Send Address: Here is the service: namespace WpfApplication1 { [ServiceContract(CallbackContract=typeof(IMyCallbackContract))] public interface IMyService { [OperationContract(IsOneWay = true)] void NewMessageToServer(string msg); [OperationContract(IsOneWay = true)] bool ServerIsResponsible(); } [ServiceContract] public interface IMyCallbackContract { [OperationContract] void NewMessageToClient(string msg); [OperationContract] void ClientIsResponsible(); } /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); //behavior.HttpGetEnabled = true; //behavior. ServiceHost serviceHost = new ServiceHost( typeof(MyService), new Uri("net.tcp://localhost:8080/")); serviceHost.Description.Behaviors.Add(behavior); serviceHost.AddServiceEndpoint( typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); serviceHost.AddServiceEndpoint( typeof(IMyService), new NetTcpBinding(), "ServiceEndpoint"); serviceHost.Open(); MessageBox.Show( "server is up"); // label1.Content = label1.Content + String.Format(" net.tcp://localhost:8080/"); } } public class MyService : IMyService { public void NewMessageToServer(string msg) { } public bool ServerIsResponsible() { return true; } } } I am getting a Xaml parse exception in Line 1, what can be the problem? Thanks!

    Read the article

  • Help with Exception Handling in ASP.NET C# Application

    - by Shrewd Demon
    hi, yesterday i posted a question regarding the Exception Handling technique, but i did'nt quite get a precise answer, partly because my question must not have been precise. So i will ask it more precisely. There is a method in my BLL for authenticating user. If a user is authenticated it returns me the instance of the User class which i store in the session object for further references. the method looks something like this... public static UsersEnt LoadUserInfo(string email) { SqlDataReader reader = null; UsersEnt user = null; using (ConnectionManager cm = new ConnectionManager()) { SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter("@Email", email); try { reader = SQLHelper.ExecuteReader(cm.Connection, "sp_LoadUserInfo", parameters); } catch (SqlException ex) { //this gives me a error object } if (reader.Read()) user = new UsersDF(reader); } return user; } now my problem is suppose if the SP does not exist, then it will throw me an error or any other SQLException for that matter. Since this method is being called from my aspx.cs page i want to return some meaning full message as to what could have gone wrong so that the user understands that there was some problem and that he/she should retry logging-in again. but i can't because the method returns an instance of the User class, so how can i return a message instead ?? i hope i made it clear ! thank you.

    Read the article

  • Getting a "No default module defined for this application" exception while running controller unit t

    - by Doron
    I have an application with the default directory structure, for an application without custom modules (see structure figure at the end). I have written a ControllerTestCase.php file as instructed in many tutorials, and I've created the appropriate bootstrap file as well (once again, see figures at the end). I've written some model tests which run just fine, but when I started writing the index controller test file, with only one test in it, with only one line in it ("$this-dispatch('/');"), I'm getting the following exception when running phpunit (but navigating with the browser to the same location - all is good and working): 1) IndexControllerTest::test_indexAction_noParams Zend_Controller_Exception: No default module defined for this application Why is this ? What have I done wrong ? Appendixes: Directory structure: -proj/ -application/ -controllers/ -IndexController.php -ErrorController.php -config/ -layouts/ -models/ -views/ -helpers/ -scripts/ -error/ -error.phtml -index/ -index.phtml -Bootstrap.php -library/ -tests/ -application/ -controllers/ -IndexControllerTest.php -models/ -bootstrap.php -ControllerTestCase.php -library/ -phpunit.xml -public/ -index.php (Basically I have some more files in the models directory, but that's not relevant to this question.) application.ini file: [production] phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 includePaths.library = APPLICATION_PATH "/../library" bootstrap.path = APPLICATION_PATH "/Bootstrap.php" bootstrap.class = "Bootstrap" appnamespace = "My" resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers" resources.frontController.params.displayExceptions = 0 resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/" resources.view[] = phpSettings.date.timezone = "America/Los_Angeles" [staging : production] [testing : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 resources.frontController.params.displayExceptions = 1 tests/application/bootstrap.php file <?php error_reporting(E_ALL); // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../application')); // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../library'), // this project' library get_include_path(), ))); /** Zend_Application */ require_once 'Zend/Application.php'; require_once 'ControllerTestCase.php';

    Read the article

  • WPF: Exception if i add a eventhandler to a MenuItem (in a ListBox)

    - by user437899
    Hi, i wanted a contextmenu for my ListBoxItems. So i created this: <ListBox Name="listBoxName"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding UserName}" /> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="ContextMenu"> <Setter.Value> <ContextMenu> <MenuItem Header="View" Name="MenuItemView" /> </ContextMenu> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> </ListBox> This works great. I have the contextmenu for all items, but if i want to add a click-eventhandler to the menuitem, like this: <MenuItem Header="View" Name="MenuItemView" Click="MenuItemView_Click" /> I get a XamlParseException when the window is created. InnerException: The Object System.Windows.Controls.MenuItem cannot be converted to type System.Windows.Controls.Grid It throws only the exception if i add a event-handler. The event-method is empty.

    Read the article

  • Exception on inserting into Access 2010 in C Sharp

    - by slao.it
    Hello, I am getting this exception when inserting into a Access 2010 database. Ex: System.Data.OleDb.OleDbException (0x80040E14): Syntax error in string in query expression ''CityName ?'. at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at ReadingData.Program.Main(String[] args) in C:\Users\user\documents\visual studio 2010\Projects\ReadingData\ReadingData\Program.cs:line 238 INSERT INTO CranbrookMain (ID,BlockNo,Plot,SubPlot,Code,Type,LastName,FirstName,ServiceHome,ServiceAddress,ServiceCity,Notes) VALUES ('1','Y','37','DS','C2','O','SMITH','John','Service Inc.','520B SLATER ROAD N.W.','CityName','CityName ? ') insertSQL = "INSERT INTO CranbrookMain (ID,BlockNo,Plot,SubPlot,Code,Type,LastName," + "FirstName,ServiceHome,ServiceAddress,ServiceCity,Notes) VALUES (" + "'"+id+ "','" + blockNo + "','" + plot + "','" + subPlot + "','" + code + "','" + type + "','" + lastname + "','" + firstname + "','" + serviceHome + "','" + serviceAddress + "','" + serviceCity + "','" + notes +"')"; Console.WriteLine(); OleDbCommand cmd = new OleDbCommand(insertSQL, con); // creating query command cmd.ExecuteNonQuery(); The error occurs in cmd.ExecuteNonQuery() function call. The above SQL INSERT statement works fine if I directly execute in the Access 2010 file.

    Read the article

  • Javascript: Uncaught exception: "too few args"

    - by Rosarch
    I think I must be making some really stupid mistake. I'm using the latest version of jQuery to write an AJAX app. function refreshGPAForTerm(term) { var meta_data = term.children('.' + TERM_META_DATA_CLASS); meta_data.children('.' + MEDIAN_GPA_CLASS).fadeOut('slow').remove(); meta_data.append(_getMedianGPAElem(term.data('GPA'))).hide().fadeIn('slow'); } function moveToTerm(original_course, helper, term) { var cloned_course = original_course.clone(true); term.data('credits', term.data('credits') + cloned_course.data('credits')); term.data('median_GPA', term.data('median_GPA') + cloned_course.data('credits') * cloned_course.data('GPA')); // error here refreshGPAForTerm(term); refreshCreditForTerm(term); original_course.addClass('already-scheduled'); original_course.draggable('disable'); cloned_course.appendTo(term).hide().fadeIn('slow').draggable(); } When refreshGPAForTerm(term) is called, Firebug displays: "Uncaught exception - Too few arguments". Stepping through in a debugger, the code then goes into jQuery. Why is this happening? What am I doing wrong?

    Read the article

  • unhandled exception Handler in .Net 3.5 SP1

    - by Ruony
    Hi. I'm converting my own web browser use WPF from Windows XP to Windows 7. when I test on Windows XP, It has no error and exceptions. But I convert and test on Windows 7 with Multi-touch Library, My Browser occurred unhandled exception. Source: PresentationCore Message: An unspecified error occurred on the render thread. StackTrace: at System.Windows.Media.MediaContext.**NotifyPartitionIsZombie**(Int32 failureCode) at System.Windows.Media.MediaContext.NotifyChannelMessage() at System.Windows.Interop.HwndTarget.HandleMessage(Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) InnerException: null I want to know where the bug occurred. That Trace Message are garbage information for me. I already googling to know that message, but i never found any information. How do I get exactly function where the bug occurred? please tell me something.

    Read the article

  • Exception in DatePickerDialog

    - by Miya
    Hi, i am trying to create a DatePickerDialog in the class 'dateDisplay.class'. I am calling this activity from 'main.class'. If I call the 'dateDisplay.class' using startActivity(), then the DatePickerDialog works fine. But actually I am using an ActivityGroup (for using tab in my application) and I am starting the 'dateDisplay.class' using the following code : Intent dateIntent=new Intent(context,dateDisplay.class); View v=getLocalActivityManager().startActivity("2",dateIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView(); setContentView(v); But an exception is caught, on calling the onCreateDialog() function. And the process is suddently stopped. It shows TargetInvocationException is occured. How can I correct the code? Following is my code: public Dialog onCreateDialog(int id,Bundle b) { Calendar c=Calendar.getInstance(); int day=c.get(Calendar.DAY_OF_MONTH); int month=c.get(Calendar.MONTH); int year=c.get(Calendar.YEAR); Dialog d = null; if(id==DATE_DIALOG_ID) { return new DatePickerDialog(this,dateChangeListener,year,month,day); } else { return null; } } Please help me.. Thank you..

    Read the article

  • C++ - Where to throw exception?

    - by HardCoder1986
    Hello! I have some kind of an ideological question, so: Suppose I have some templated function template <typename Stream> void Foo(Stream& stream, Object& object) { ... } which does something with this object and the stream (for example, serializes that object to the stream or something like that). Let's say I also add some plain wrappers like (and let's say the number of these wrappers equals 2 or 3): void FooToFile(const std::string& filename, Object& object) { std::ifstream stream(filename.c_str()); Foo(stream, object); } So, my question is: Where in this case (ideologically) should I throw the exception if my stream is bad? Should I do this in each wrapper or just move that check to my Foo, so that it's body would look like if (!foo.good()) throw (something); // Perform ordinary actions I understand that this may be not the most important part of coding and these solutions are actually equal, but I just wan't to know "the proper" way to implement this. Thank you.

    Read the article

  • How to avoid this PDO exception: Cannot execute queries while other unbuffered queries are active

    - by Vittorio Vittori
    Hi, I'd like to print a simple table in my page with 3 columns, building name, tags and architecture style. If I try to retrieve the list of building names and arch. styles there is no problem: SELECT buildings.name, arch_styles.style_name FROM buildings INNER JOIN buildings_arch_styles ON buildings.id = buildings_arch_styles.building_id INNER JOIN arch_styles ON arch_styles.id = buildings_arch_styles.arch_style_id LIMIT 0, 10 My problem starts on retreaving the first 5 tags for every building of the query I've just wrote. SELECT DISTINCT name FROM tags INNER JOIN buildings_tags ON buildings_tags.tag_id = tags.id AND buildings_tags.building_id = 123 LIMIT 0, 5 The query itself works perfectly, but not where I thought to use it: <?php // pdo connection allready active, i'm using mysql $pdo_conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); $sql = "SELECT buildings.name, buildings.id, arch_styles.style_name FROM buildings INNER JOIN buildings_arch_styles ON buildings.id = buildings_arch_styles.building_id INNER JOIN arch_styles ON arch_styles.id = buildings_arch_styles.arch_style_id LIMIT 0, 10"; $buildings_stmt = $pdo_conn->prepare ($sql); $buildings_stmt->execute (); $buildings = $buildings_stmt->fetchAll (PDO::FETCH_ASSOC); $sql = "SELECT DISTINCT name FROM tags INNER JOIN buildings_tags ON buildings_tags.tag_id = tags.id AND buildings_tags.building_id = :building_id LIMIT 0, 5"; $tags_stmt = $pdo_conn->prepare ($sql); $html = "<table>"; // i'll use it to print my table foreach ($buildings as $building) { $name = $building["name"]; $style = $building["style_name"]; $id = $building["id"]; $tags_stmt->bindParam (":building_id", $id, PDO::PARAM_INT); $tags_stmt->execute (); // the problem is HERE $tags = $tags_stmt->fetchAll (PDO::FETCH_ASSOC); $html .= "... $name ... $style"; foreach ($tags as $current_tag) { $tag = $current_tag["name"]; $html .= "... $tag ..."; // let's suppose this is an area of the table where I print the first 5 tags per building } } $html .= "...</table>"; print $html; I'm not experienced on queries, so i though something like this, but it throws the error: PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. What can I do to avoid this? Should I change all and search a different way to get this kind of queries?

    Read the article

  • how to: handle exceptions, best practices

    - by b0x0rz
    need to implement a global error handling, so maybe you can help out with the following example... i have this code: public bool IsUserAuthorizedToSignIn(string userEMailAddress, string userPassword) { // get MD5 hash for use in the LINQ query string passwordSaltedHash = this.PasswordSaltedHash(userEMailAddress, userPassword); // check for email / password / validity using (UserManagementDataContext context = new UserManagementDataContext()) { var users = from u in context.Users where u.UserEMailAdresses.Any(e => e.EMailAddress == userEMailAddress) && u.UserPasswords.Any(p => p.PasswordSaltedHash == passwordSaltedHash) && u.IsActive == true select u; // true if user found return (users.Count() == 1) ? true : false; } } and the md5 as well: private string PasswordSaltedHash(string userEMailAddress, string userPassword) { MD5 hasher = MD5.Create(); byte[] data = hasher.ComputeHash(Encoding.Default.GetBytes(userPassword + userEMailAddress)); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { stringBuilder.Append(data[i].ToString("x2")); } Trace.WriteLine(String.Empty); Trace.WriteLine("hash: " + stringBuilder.ToString()); return stringBuilder.ToString(); } so, how would i go about handling exceptions from these functions? they first one is called from the Default.aspx page. the second one is only called from other functions from the class library. what is the best practice? surround code INSIDE each function with try-catch surround the FUNCTION CALL with try-catch something else?? what to do if exceptions happen? in this example: this is a user sign in, so somehow even if everything fails, the user should get some meaningful info - along the lines: sign in ok (just redirect), sign in not ok (wrong user name / password), sign in not possible due to internal problems, sorry (exception happened). for the first function i am worried if there is a problem with database access. not sure if there is anything that needs to be handled in the second one. thnx for the info. how would you do it? need specific info on this (easier for me to understand), but also general info on how to handle other tasks/functions. i looked around the internet but everyone has different things to say, so unsure what to do... will go with either most votes here, or most logicaly explained answer :) thank you.

    Read the article

  • Better way to ignore exception type: multiple catch block vs. type querying

    - by HuBeZa
    There are situations that we like to ignore a specific exception type (commonly ObjectDisposedException). It can be achieved with those two methods: try { // code that throws error here: } catch (SpecificException) { /*ignore this*/ } catch (Exception ex) { // Handle exception, write to log... } or try { // code that throws error here: } catch (Exception ex) { if (ex is SpecificException) { /*ignore this*/ } else { // Handle exception, write to log... } } What are the pros and cons of this two methods (regarding performance, readability, etc.)?

    Read the article

  • FolderClosed Exception in Javamail

    - by SikhWarrior
    Im trying to create a simple mail client in android, and I have the android version of javamail compiling and running in my app. However, whenever I try to connect and receive mail, I get a Folder Closed exception seen below. 10-23 12:12:13.484: W/System.err(6660): javax.mail.FolderClosedException 10-23 12:12:13.484: W/System.err(6660): at com.sun.mail.imap.IMAPMessage.getProtocol(IMAPMessage.java:149) 10-23 12:12:13.484: W/System.err(6660): at com.sun.mail.imap.IMAPMessage.loadBODYSTRUCTURE(IMAPMessage.java:1262) 10-23 12:12:13.484: W/System.err(6660): at com.sun.mail.imap.IMAPMessage.getDataHandler(IMAPMessage.java:616) 10-23 12:12:13.484: W/System.err(6660): at javax.mail.internet.MimeMessage.getContent(MimeMessage.java:1398) 10-23 12:12:13.484: W/System.err(6660): at com.teamzeta.sfu.Util.MailHelper.getMessageHTML(MailHelper.java:60) 10-23 12:12:13.484: W/System.err(6660): at com.teamzeta.sfu.GetAsyncEmails.onPostExecute(EmailActivity.java:31) 10-23 12:12:13.484: W/System.err(6660): at com.teamzeta.sfu.GetAsyncEmails.onPostExecute(EmailActivity.java:1) 10-23 12:12:13.484: W/System.err(6660): at android.os.AsyncTask.finish(AsyncTask.java:631) 10-23 12:12:13.484: W/System.err(6660): at android.os.AsyncTask.access$600(AsyncTask.java:177) 10-23 12:12:13.484: W/System.err(6660): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) 10-23 12:12:13.484: W/System.err(6660): at android.os.Handler.dispatchMessage(Handler.java:99) 10-23 12:12:13.484: W/System.err(6660): at android.os.Looper.loop(Looper.java:137) 10-23 12:12:13.484: W/System.err(6660): at android.app.ActivityThread.main(ActivityThread.java:5227) 10-23 12:12:13.484: W/System.err(6660): at java.lang.reflect.Method.invokeNative(Native Method) 10-23 12:12:13.484: W/System.err(6660): at java.lang.reflect.Method.invoke(Method.java:511) 10-23 12:12:13.484: W/System.err(6660): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795) 10-23 12:12:13.484: W/System.err(6660): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562) 10-23 12:12:13.494: W/System.err(6660): at dalvik.system.NativeStart.main(Native Method) My code is as follows: public static Message[] getAllMail(String user, String pwd){ String host = "imap.sfu.ca"; final Message[] NO_MESSAGES = {}; Properties properties = System.getProperties(); properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("mail.imap.socketFactory.port", "993"); Session session = Session.getDefaultInstance(properties); try { Store store = session.getStore("imap"); store.connect(host, user, pwd); Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); folder.close(true); store.close(); Log.d("####TEAM ZETA DEBUG####", "Content: " + messages.length); return messages; } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("####TEAM ZETA DEBUG####", "Returning NO_MESSAGES"); return NO_MESSAGES; } public static String getMessageHTML(Message message){ Object msgContent; try { msgContent = message.getContent(); if (msgContent instanceof Multipart) { Multipart mp = (Multipart) msgContent; for (int i = 0; i < mp.getCount(); i++) { BodyPart bp = mp.getBodyPart(i); if (Pattern .compile(Pattern.quote("text/html"), Pattern.CASE_INSENSITIVE) .matcher(bp.getContentType()).find()) { // found html part return (String) bp.getContent(); } else { // some other bodypart... } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "Something went wrong"; } I couldn't find anything helpful on the web, does anyone have an ideas why this is happening?? This is called in class GetAsyncEmails extends AsyncTask<String, Integer, Message[]>{ @Override protected Message[] doInBackground(String... args) { // TODO Auto-generated method stub Message[] messages = MailHelper.getAllMail(args[0], args[1]); return messages; } protected void onPostExecute(Message[] result){ if(result.length > 1){ Message message = result[0]; String content = MailHelper.getMessageHTML(message); System.out.println("####TEAM ZETA DEBUG####" + content); } } }

    Read the article

  • "Randomly" occurring errors...

    - by ClarkeyBoy
    Hi, My website has a setup whereby when the application starts a module called SiteContent is "created". This runs a clearup function which basically deletes any irrelevant data from the database, in case any has been left in there from previously run functions. The module has instances of Manager classes - namely RangeManager, CollectionManager, DesignManager. There are others but I will just use these as an example. Each Manager class contains an array of items - items may be of type Range, Collection or Design, whichever one is relevant. Data for each range is then read into an instance of Range, Collection or Design. I know this is basically duplicating data - not very efficient but its my final year project at the moment so I can always change it to use Linq or something similar later, when I am not pressured by the one month deadline. I have a form which, on clicking the Save button, saves data by calling SiteContent.RangeManager.Create(vars) or SiteContent.RangeManager.Update(Range As Range, vars) (or the equivalent for other manager classes, whichever one happens to be relevant). These functions call a stored procedure to insert or update in the relevant table. Classes Range, Collection and Design all have attributes such as Name, Description, Display and several others. When the Create or Update function is called, the Manager loops through all the other items to check if an item with the same name already exists. The Update function ensures that it does not compare the item being updated to itself. A custom exception (ItemAlreadyExistsException) is thrown if another item with the same name is found. For some weird reason, if I go into a Range, Collection or Design in edit mode, change something and try to update it, it occasionally doesnt update the item. When I say occasionally I mean every 3 - 4 page loads, sometimes more. I see absolutely no pattern in when or why it occurs. I have a try-catch statement which catches ItemAlreadyExistsException, and outputs "An item with this name already exists" when caught. Occasionally it will output this; other times it will not. Does anyone have any idea why this could happen? Maybe a mistake which someone has made and solved before? I used to have regular expressions in place that the names were compared to - I believe it was [a-zA-Z]{1, 100} (between 1 and 100 lower- or upper-case characters). For some reason the customer who I am developing the site for used to get errors saying its not in the correct format. Yet he could try the same text 5 minutes later and it would work fine. I am thinking this could well be the same problem, since both problems occur at random. Many thanks in advance. Regards, Richard Clarke Edit: After much time spent narrowing down the code, I have decided to wait till my brother, who has been a programmer for at least 8 years more than I have, to come down over Easter and get him to have a look at it. If he cant solve it then I will zip the files up and put them somewhere for people to access and have a go at. I narrowed it down literally to the minimum number of files possible, and it still occurs. It seems to be about every 10th time. Having said that, I force the manager classes to refresh every 10 page loads or 5 minutes (whichever one is sooner). I may look into this - this could be causing a problem. Basically each Manager contains an array of an object. This array is populated using data from the database. The Update function takes an instance of the item and the new values to be set for the object. If it happens to be a page load where the array is reset (ie the data is loaded freshly from the database) then the object instance with the same ID wont be the same instance as the one being passed in. This explains the fact that it throws an ItemAlreadyExistsException now and then. It all makes sense now the more I think about it. If I were to pass in the ID of the object to be altered, rather than the object itself, then it should work perfectly. I will answer the question if I solve it..

    Read the article

  • Enterprise Library Logging / Exception handling and Postsharp

    - by subodhnpushpak
    One of my colleagues came-up with a unique situation where it was required to create log files based on the input file which is uploaded. For example if A.xml is uploaded, the corresponding log file should be A_log.txt. I am a strong believer that Logging / EH / caching are cross-cutting architecture aspects and should be least invasive to the business-logic written in enterprise application. I have been using Enterprise Library for logging / EH (i use to work with Avanade, so i have affection towards the library!! :D ). I have been also using excellent library called PostSharp for cross cutting aspect. Here i present a solution with and without PostSharp all in a unit test. Please see full source code at end of the this blog post. But first, we need to tweak the enterprise library so that the log files are created at runtime based on input given. Below is Custom trace listner which writes log into a given file extracted out of Logentry extendedProperties property. using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; using Microsoft.Practices.EnterpriseLibrary.Logging; using System.IO; using System.Text; using System; using System.Diagnostics;   namespace Subodh.Framework.Logging { [ConfigurationElementType(typeof(CustomTraceListenerData))] public class LogToFileTraceListener : CustomTraceListener {   private static object syncRoot = new object();   public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) {   if ((data is LogEntry) & this.Formatter != null) { WriteOutToLog(this.Formatter.Format((LogEntry)data), (LogEntry)data); } else { WriteOutToLog(data.ToString(), (LogEntry)data); } }   public override void Write(string message) { Debug.Print(message.ToString()); }   public override void WriteLine(string message) { Debug.Print(message.ToString()); }   private void WriteOutToLog(string BodyText, LogEntry logentry) { try { //Get the filelocation from the extended properties if (logentry.ExtendedProperties.ContainsKey("filelocation")) { string fullPath = Path.GetFullPath(logentry.ExtendedProperties["filelocation"].ToString());   //Create the directory where the log file is written to if it does not exist. DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(fullPath));   if (directoryInfo.Exists == false) { directoryInfo.Create(); }   //Lock the file to prevent another process from using this file //as data is being written to it.   lock (syncRoot) { using (FileStream fs = new FileStream(fullPath, FileMode.Append, FileAccess.Write, FileShare.Write, 4096, true)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) { Log(BodyText, sw); sw.Close(); } fs.Close(); } } } } catch (Exception ex) { throw new LoggingException(ex.Message, ex); } }   /// <summary> /// Write message to named file /// </summary> public static void Log(string logMessage, TextWriter w) { w.WriteLine("{0}", logMessage); } } }   The above can be “plugged into” the code using below configuration <loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="Trace" logWarningsWhenNoCategoriesMatch="true"> <listeners> <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Subodh.Framework.Logging.LogToFileTraceListener, Subodh.Framework.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Subodh Custom Trace Listener" initializeData="" formatter="Text Formatter" /> </listeners> Similarly we can use PostSharp to expose the above as cross cutting aspects as below using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using PostSharp.Laos; using System.Diagnostics; using GC.FrameworkServices.ExceptionHandler; using Subodh.Framework.Logging;   namespace Subodh.Framework.ExceptionHandling { [Serializable] public sealed class LogExceptionAttribute : OnExceptionAspect { private string prefix; private MethodFormatStrings formatStrings;   // This field is not serialized. It is used only at compile time. [NonSerialized] private readonly Type exceptionType; private string fileName;   /// <summary> /// Declares a <see cref="XTraceExceptionAttribute"/> custom attribute /// that logs every exception flowing out of the methods to which /// the custom attribute is applied. /// </summary> public LogExceptionAttribute() { }   /// <summary> /// Declares a <see cref="XTraceExceptionAttribute"/> custom attribute /// that logs every exception derived from a given <see cref="Type"/> /// flowing out of the methods to which /// the custom attribute is applied. /// </summary> /// <param name="exceptionType"></param> public LogExceptionAttribute( Type exceptionType ) { this.exceptionType = exceptionType; }   public LogExceptionAttribute(Type exceptionType, string fileName) { this.exceptionType = exceptionType; this.fileName = fileName; }   /// <summary> /// Gets or sets the prefix string, printed before every trace message. /// </summary> /// <value> /// For instance <c>[Exception]</c>. /// </value> public string Prefix { get { return this.prefix; } set { this.prefix = value; } }   /// <summary> /// Initializes the current object. Called at compile time by PostSharp. /// </summary> /// <param name="method">Method to which the current instance is /// associated.</param> public override void CompileTimeInitialize( MethodBase method ) { // We just initialize our fields. They will be serialized at compile-time // and deserialized at runtime. this.formatStrings = Formatter.GetMethodFormatStrings( method ); this.prefix = Formatter.NormalizePrefix( this.prefix ); }   public override Type GetExceptionType( MethodBase method ) { return this.exceptionType; }   /// <summary> /// Method executed when an exception occurs in the methods to which the current /// custom attribute has been applied. We just write a record to the tracing /// subsystem. /// </summary> /// <param name="context">Event arguments specifying which method /// is being called and with which parameters.</param> public override void OnException( MethodExecutionEventArgs context ) { string message = String.Format("{0}Exception {1} {{{2}}} in {{{3}}}. \r\n\r\nStack Trace {4}", this.prefix, context.Exception.GetType().Name, context.Exception.Message, this.formatStrings.Format(context.Instance, context.Method, context.GetReadOnlyArgumentArray()), context.Exception.StackTrace); if(!string.IsNullOrEmpty(fileName)) { ApplicationLogger.LogException(message, fileName); } else { ApplicationLogger.LogException(message, Source.UtilityService); } } } } To use the above below is the unit test [TestMethod] [ExpectedException(typeof(NotImplementedException))] public void TestMethod1() { MethodThrowingExceptionForLog(); try { MethodThrowingExceptionForLogWithPostSharp(); } catch (NotImplementedException ex) { throw ex; } }   private void MethodThrowingExceptionForLog() { try { throw new NotImplementedException(); } catch (NotImplementedException ex) { // create file and then write log ApplicationLogger.TraceMessage("this is a trace message which will be logged in Test1MyFile", @"D:\EL\Test1Myfile.txt"); ApplicationLogger.TraceMessage("this is a trace message which will be logged in YetAnotherTest1Myfile", @"D:\EL\YetAnotherTest1Myfile.txt"); } }   // Automatically log details using attributes // Log exception using attributes .... A La WCF [FaultContract(typeof(FaultMessage))] style] [Log(@"D:\EL\Test1MyfileLogPostsharp.txt")] [LogException(typeof(NotImplementedException), @"D:\EL\Test1MyfileExceptionPostsharp.txt")] private void MethodThrowingExceptionForLogWithPostSharp() { throw new NotImplementedException(); } The good thing about the approach is that all the logging and EH is done at centralized location controlled by PostSharp. Of Course, if some other library has to be used instead of EL, it can easily be plugged in. Also, the coder ARE ONLY involved in writing business code in methods, which makes code cleaner. Here is the full source code. The third party assemblies provided are from EL and PostSharp and i presume you will find these useful. Do let me know your thoughts / ideas on the same. Technorati Tags: PostSharp,Enterprize library,C#,Logging,Exception handling

    Read the article

  • Exception when creating MailMessage

    - by Julien Poulin
    I'm getting a FormatException telling me the address '[email protected]' is invalid (I'm guessing because of the '-'). Here is the code I'm using: var md = new MailDefinition(); md.BodyFileName = physicalPath; md.Subject = subject; md.From = from; md.CC = cc; md.IsBodyHtml = true; MailMessage mailMessage = md.CreateMailMessage(to, replacements, owner); Is there a bug in the .Net e-mail parser? I am sure this address is valid since it belongs to a friend and I have no problem sending and receiving his e-mails with Outlook. Is there a way to fix this? EDIT: Here is the stacktrace: [FormatException: La chaîne spécifiée n'est pas de la forme requise pour une adresse de messagerie.] System.Net.Mime.MailBnfHelper.ReadMailAddress(String data, Int32& offset, String& displayName) +1141755 System.Net.Mail.MailAddress.ParseValue(String address) +240 System.Net.Mail.MailAddress..ctor(String address, String displayName, Encoding displayNameEncoding) +85 System.Net.Mail.Message..ctor(String from, String to) +122 System.Net.Mail.MailMessage..ctor(String from, String to) +114 System.Web.UI.WebControls.MailDefinition.CreateMailMessage(String recipients, IDictionary replacements, String body, Control owner) +1366 System.Web.UI.WebControls.MailDefinition.CreateMailMessage(String recipients, IDictionary replacements, Control owner) +290 WebNotificationManager.CreateMessage(Page owner, MessageTemplate messageTemplate, ListDictionary replacements, String to, String from, String cc, String subject) in c:\dev\SoccerMania\SoccerMania\App_Code\WebNotificationManager.cs:41 WebNotificationManager.SendMessage(Page owner, MessageTemplate messageTemplate, ListDictionary replacements, String to, String subject) in c:\dev\SoccerMania\SoccerMania\App_Code\WebNotificationManager.cs:22 inscription.bInscription_Click(Object sender, EventArgs e) in c:\dev\SoccerMania\SoccerMania\Inscription.aspx.cs:54 System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +111 System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +79 System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >