Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Thursday, 28 March 2013

Search string in CSV

Question is:

I have a string called inputstring. I'd like to search a CSV file to find all instances of the inputstring? How is this done in c#?

Ans:

namespace CSV_search_string

{

    class Program

    {

        static void Main(string[] args)

        {

            string csvFile = "SciFi Books.csv";

            string searchString = "Fred Hoyle";

            char csvSeparator = ',';

 

            foreach (string line in File.ReadLines(csvFile))

                foreach (string value in line.Replace("\"", "").Split('\r', '\n', csvSeparator))

                    if (value.Trim() == searchString.Trim()) // case sensitive

                        Console.WriteLine("[ {0} ] found in: {1}", value, line);

 

            Console.ReadKey();

        }

    }

}

Monday, 28 January 2013

Encrypting a File

Cryptography is an indispensable tool for protecting information in computer systems.Cryptography plays an important role in Security. You Encrypt and Decrypt the information using cryptography.

ncrypt the File using DES (Data Encryption standard) algorithm.

1.Using Visual Studio create a project

2.Add the following assembly on the page

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.IO;
sing Microsoft.VisualBasic;

3.Now write the Code in the Page

public class CrytographySample
{
    public static void Main()
    {
         try
        {
            DESCryptoServiceProvider sampleDESProvider = new DESCryptoServiceProvider();
             sampleDESProvider.Key = ASCIIEncoding.ASCII.GetBytes("987654321");
            sampleDESProvider.IV = ASCIIEncoding.ASCII.GetBytes("Architais@HM");

            ICryptoTransform sampleCryptoTransform = myDESProvider.CreateEncryptor(sampleDESProvider.Key ,sampleDESProvider.IV );

            FileStream SampleInFileStream = new FileStream("sample.txt", FileMode.Open, FileAccess.Read);
            FileStream SampleOutFileStream = new FileStream("SampleDes.txt", FileMode.Create, FileAccess.Write);
            CryptoStream sampleCryptoStream = new CryptoStreamSampleOutFileStream sampleCryptoTransform ,CryptoStreamMode.Write);
             byte[] bytearraysample = new byte[SampleInFileStream .Length];
             SampleInFileStream .Read(bytearrayinput, 0, bytearrayinput.Length);
            sampleCryptoStream.Write(bytearrayinput, 0, bytearrayinput.Length);
             sampleCryptoStream.Close();
            SampleInFileStream.Close();
            SampleOutFileStream.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

4.Now create a text file in the folder appliation bin folder with some text.

5. Run the application.
Yollla! the text is encrypted.
In case you find any difficulties in doing this. Send a mail to me.

Sending and Logging Custom Errors in ASP.Net MVC

When you set the custom errors as remote only , you basically want to use the errors for debugging and fixing the problems.

There are various ways how you can use the very useful information from custom errors and notify these errors to the website administrators within no time.

Notifications can happen in many different ways out of which following are the most used:
a. Use Event Log on the server system.
b. Use log tables in SQL Server to log errors.
c. Write error log on to a text file and save them in folders.
d. Send Email to admin(s) with relevant information.
e. Send pager/sms with relevant information to the admin/maintenance team.

Notification of the error can be sent to the administrator in one of the following two ways:
1) Error can be registered as a log entry in the Windows Event Log on the administrator's machine
 2) An Email can be sent to the administrator with a suitable error message
Writing to the Event Log

In ASP.NET, error can be handled programmatically by writing appropriate code in the page-level error event, for errors on an individual page or in the application-level error event for handling errors that may occur in any page of the application.
Therefore, code for writing in the Event Log should be written in either of the events, depending on the requirement of the application. To illustrate this example, I have written the code in the application-level event with the error mode set to "RemoteOnly" and the defaultRedirect attribute to error.htm. The application-level error event should be included in the global file global.asax within the same application folder.

Event Log support is provided in .NET through the namespace System.Diagnostics.

SMTP mail service support is provided in .NET through the namespace System.Web.Mail.

To Log the errors into SQL, create a log table and use ADO.Net classes to write the errors.

To Log error on to text file use System. IO

To send message use System.Net

Send a mail across to me in case you want to implement any of these methods but are confused/need help to implement this.


Custom Errors in ASP.NET

What are Custom Errors?

There are certain errors/exceptions which are thrown by the operating system or the dot net framework when doing application programming we need to handle these errors properly. Dot net provides various ways to handle these kind of exceptions using CLR.
There are some errors which are application specific , there are also some errors which may pop-up in your application in adverse scenarios. When these kind of errors/exceptions are not handled properly ASP.NET shows a default error page that gives a brief description of the error along with the line number on which the error occurred. This page reveals a lot of information to the public , which may be dangerous when the information gets into wrong hands. Although these error pages are useful to a developer , who would wish to view this default error page, during the testing of the application since the description helps him in rectifying the error. But you would never want a user trying to access his application, to view this error page. The user would be least bothered to know about the error. Instead of showing the default error page, you should show a customized error page that would let the user send notification of the error to the administrator.
  
There are three different ways you can handle errors in ASP.Net.
Following are the error modes in which an ASP.NET application can work:
1) Off Mode
 2) On Mode
 3) RemoteOnly Mode

 By default, the mode value is set to "RemoteOnly".

Off Mode :When the error attribute is set to "Off", ASP.NET uses its default error page for both local and remote users in case of an error.

On Mode :In case of "On" Mode, ASP.NET uses user-defined custom error page instead of its default error page for both local and remote users. If a custom error page is not specified, ASP.NET shows the error page describing how to enable remote viewing of errors.

RemoteOnly :ASP.NET error page is shown only to local users. Remote requests will first check the configuration settings for the custom error page or finally show an IIS error.

You need to customize error page implementatio in configuration file by adding a value for an attribute defaultRedirect in the <customErrors> tag of the configuration file web.config.

This file determines configuration settings for the underlying application.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.web>
         <customErrors mode="Off" />
    </system.web>
</configuration>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.web>
         <customErrors defaultRedirect="error.htm" mode="On" />
    </system.web>
</configuration>
RemoteOnly Mode
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.web>
         <customErrors defaultRedirect="error.htm" mode="RemoteOnly" />
    </system.web>
</configuration>

In the next article we will see how we can send errors to administrators.

Sunday, 27 January 2013

How to add double quotes in a string

Often we face situations where we need to add double quotes in a string.

In C# following is the way I have found out to add double quotes to a string.

1. Add escape characters to string by doubling them (verbatim string literal):

var str = @"""doublequotes""";
var string1 = @"firstpart ""part in quotes"" laterpart";

2. Add a normal string literal you escape them with a \:

string str = "\"doublequotes\"";
var string2 = "firstpart\"part in quotes\" laterpart";

When working on asp.net , you can try following.

  string title = string.Format("<div>\"{0}\"</div>", "text to be filled");

You can also use: 

  &dquo;
<div>&dquo;"+ title +@"&dquo;</div>

or escape the double quote
\"
<div>\""+ title +@"\"</div>


Friday, 4 January 2013

Windows 8 : Contact Picker

Suppose you want to create an application which uses mailing , messaging , appointments and social networking.  And you want to access existing contacts rather than adding your own contact, in this case Windows 8 provides you with the Contact Picker API.

Using Contact Picker API you can:
  • Add a contact
  • Pick a contact
  • Pick multiple contacts

Basically the Contact Picker API and ContactPicker class enables apps that to select and acquire info about contacts.

Namespace used is: Windows.ApplicationModel.Contacts

Following are the various classes in this namespace:

Contact
Creates a new contact.
ContactField
Shows a piece of contact data.
ContactFieldFactory
Creates fields that contain information about a contact.
ContactInformation
Contains the information about a contact.
ContactInstantMessageField
Defines a field that is an instant messaging (IM) address.
ContactLocationField
Contains information about a user's location and address.
ContactPicker
Controls how the Contact Picker user interface opens and what information it shows.
KnownContactField
A static class that contains the names of contact fields for storing commonly requested information like email address and phone numbers.

 

In the following example we will use:
  • ContactPicker class
  • ContactInformation class

In this demo I am trying to:
  • Open all the contact information available with me.
  • Select single information.
  • Display the data fetched from the contact information.

The namespaces I added for this sample are:
  • using Windows.ApplicationModel.Contacts;
  • using System.Text;
  • using Windows.Storage.Streams;
  • using Windows.UI.Xaml.Media.Imaging;

In the xaml file , I have six text blocks and one button called ‘pick single contact’

 

When the button is clicked , user is prompted with a screen which lists all the contacts that I have on my Windows 8 device.
I can select a single contact and on clicking the OK button the screen details the contact details of the contact selected in the previous screen.
For the above contact there is no address added, so the address field is empty. If the address fields are present in the contact information the address is also shown.

Now, let us look the xaml code.

<Page
    x:Class="ContactPicker.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ContactPicker"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
 
    <Grid Background="#FFF73131">
        <Image x:Name="OutputThumbnail" Grid.Column="0" Stretch="None" VerticalAlignment="Top" HorizontalAlignment="Left"/>
        <Button Content="Pick Single Contact " HorizontalAlignment="Left" Margin="581,145,0,0" VerticalAlignment="Top" Width="299" Name="PickContact" Click="PickContact_Click" Height="105" FontFamily="Segoe UI Light" FontSize="24" IsDoubleTapEnabled="False">
              <Button.Projection>
                     <PlaneProjection RotationX="-4" RotationY="-6"/>
              </Button.Projection>
        </Button>
        <TextBlock HorizontalAlignment="Left" Margin="704,270,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="56" Width="391" Visibility="Collapsed" Name="contactName" RenderTransformOrigin="0.502,5.966" FontFamily="Segoe UI Light" FontSize="32"/>
        <TextBlock HorizontalAlignment="Left" Margin="411.73,271.356,0,0" TextWrapping="Wrap" Text="Contact Name" VerticalAlignment="Top" Height="60.337" Width="247.325" Visibility="Visible" x:Name="contactNameLabel" RenderTransformOrigin="0.502,5.966" FontFamily="Segoe UI Light" FontSize="32" UseLayoutRounding="False" d:LayoutRounding="Auto">
            <TextBlock.RenderTransform>
                <CompositeTransform Rotation="0.166"/>
            </TextBlock.RenderTransform>
        </TextBlock>
        <TextBlock HorizontalAlignment="Left" Margin="413.223,351.953,0,0" TextWrapping="Wrap" Text="Email" VerticalAlignment="Top" Height="60.337" Width="247.325" Visibility="Visible" x:Name="Email" RenderTransformOrigin="0.502,5.966" FontFamily="Segoe UI Light" FontSize="32" UseLayoutRounding="False" d:LayoutRounding="Auto">
            <TextBlock.RenderTransform>
                <CompositeTransform Rotation="0.166"/>
            </TextBlock.RenderTransform>
        </TextBlock>
        <TextBlock HorizontalAlignment="Left" Margin="698,348,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Height="117" Width="582" Visibility="Visible" x:Name="EmailValue" RenderTransformOrigin="0.502,5.966" FontFamily="Segoe UI Light" FontSize="32"/>
        <TextBlock HorizontalAlignment="Left" Margin="413.223,516.132,0,0" TextWrapping="Wrap" Text="Address" VerticalAlignment="Top" Height="60.337" Width="247.325" Visibility="Visible" x:Name="Address" RenderTransformOrigin="0.502,5.966" FontFamily="Segoe UI Light" FontSize="32" UseLayoutRounding="False" d:LayoutRounding="Auto">
            <TextBlock.RenderTransform>
                <CompositeTransform Rotation="0.166"/>
            </TextBlock.RenderTransform>
        </TextBlock>
        <TextBlock HorizontalAlignment="Left" Margin="682,464,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Height="241" Width="589" Visibility="Visible" x:Name="AddressValue" RenderTransformOrigin="0.502,5.966" FontFamily="Segoe UI Light" FontSize="32"/>
 
 
    </Grid>
</Page>

 

The xaml code is nothing but a very simple xaml page.

Now , Let us do the button click event:

1.       Create an object of the Contact class

var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker();

2.       Now , we need to fetch the contact information using the ContactInformation class:

ContactInformation contact = await contactPicker.PickSingleContactAsync();

 

PickSingleContactAsync(); is the method which internally collates all the contact information from my OS and presents to me on the UI.

 

When implementing PickSingleContactAsync();This method has no parameters. Using this method I can select only one contact at a time.

 

Once , I have selected a contact , the contact information is now available , we need to fetch the information and show them in appropriate format.

 

                contactName.Visibility = Visibility.Visible;

                AddressValue.Text = string.Empty;

                contactName.Text = contact.Name;

                EmailValue.Visibility = Visibility.Visible;

                EmailValue.Text = contact.Emails[0].Value.ToString();

                if (contact.Locations.Count > 0)

                {

                    string street = contact.Locations[0].Street.ToString();

                    string city = contact.Locations[0].City.ToString();

                    string category = contact.Locations[0].Category.ToString();

                    string region = contact.Locations[0].Region.ToString();

                    string country = contact.Locations[0].Country.ToString();

 

                    string postalCode = contact.Locations[0].PostalCode.ToString();

                    string address = street + city + region + country + postalCode;

                    AddressValue.Visibility = Visibility.Visible;

                    AddressValue.Text = address;

           }

 

Although , I can get the all the contact information using this, I cannot get the thumbnail information using contact class.

So,  Let us try to fetch the thumbnail information.

To fetch the thumbnail information ,

 IRandomAccessStreamWithContentType stream = await contact.GetThumbnailAsync();

 

And once , you have fetched the image stream use following:

               if (stream != null && stream.Size > 0)

                {

                    BitmapImage bitmap = new BitmapImage();

                    bitmap.SetSource(stream);

                    OutputThumbnail.Source = bitmap;

                }

                else

                {

                    OutputThumbnail.Source = null;

         }

 

So,  the .cs file now looks like:

 

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Navigation;

using Windows.ApplicationModel.Contacts;

using System.Text;

using Windows.Storage.Streams;

using Windows.UI.Xaml.Media.Imaging;

 

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

 

namespace ContactPicker

{

    /// <summary>

    /// An empty page that can be used on its own or navigated to within a Frame.

    /// </summary>

    public sealed partial class MainPage : Page

    {

        public MainPage()

        {

            this.InitializeComponent();

        }

 

        /// <summary>

        /// Invoked when this page is about to be displayed in a Frame.

        /// </summary>

        /// <param name="e">Event data that describes how this page was reached.  The Parameter

        /// property is typically used to configure the page.</param>

        protected override void OnNavigatedTo(NavigationEventArgs e)

        {

        }

 

     

        private async void PickContact_Click(object sender, RoutedEventArgs e)

        {

            var contactPicker = new Windows.ApplicationModel.Contacts.ContactPicker();

            ContactInformation contact = await contactPicker.PickSingleContactAsync();

            if (contact != null)

            {

                contactName.Visibility = Visibility.Visible;

                AddressValue.Text = string.Empty;

                contactName.Text = contact.Name;

                EmailValue.Visibility = Visibility.Visible;

                EmailValue.Text = contact.Emails[0].Value.ToString();

                if (contact.Locations.Count > 0)

                {

                    string street = contact.Locations[0].Street.ToString();

                    string city = contact.Locations[0].City.ToString();

                    string category = contact.Locations[0].Category.ToString();

                    string region = contact.Locations[0].Region.ToString();

                    string country = contact.Locations[0].Country.ToString();

 

                    string postalCode = contact.Locations[0].PostalCode.ToString();

                    string address = street + city + region + country + postalCode;

                    AddressValue.Visibility = Visibility.Visible;

                    AddressValue.Text = address;

                }

 

                IRandomAccessStreamWithContentType stream = await contact.GetThumbnailAsync();

                if (stream != null && stream.Size > 0)

                {

                    BitmapImage bitmap = new BitmapImage();

                    bitmap.SetSource(stream);

                    OutputThumbnail.Source = bitmap;

                }

                else

                {

                    OutputThumbnail.Source = null;

                }

 

            }

       }

           

    }

 

  

  

}