Thursday 10 December 2015

auto-format-entered-date-onkeypress

  C# textbox.Attributes.Add("onkeyup", "javascript:return getDate(event);");

JavaScript


 function getDate(elem){
var elemVal = elem.value;
var elemId = elem.id;

switch(elemVal.length){
case 2:
elemVal = elemVal+"/";
break;
case 5:
elemVal = elemVal+"/";
break;
}
document.getElementById(elemId).value = elemVal;
}


Sunday 6 December 2015

Download feature not working within update-panel in asp-net






You cannot return an attachment in an UpdatePanel partial postback, since the results are used by the ScriptManager to update a DIV (not the whole response). The simplest fix for what you're trying to do would be to make your download button as a postback control. That would cause that button to initiate a full postback. Here's the code below to include in your Page_Load


ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(this.lnkDownload);

Thursday 3 December 2015

Transpose a data table in C#

 private DataTable GenerateTransposedTable(DataTable inputTable)
        {
            DataTable outputTable = new DataTable();

            // Add columns by looping rows

            // Header row's first column is same as in inputTable
            outputTable.Columns.Add(inputTable.Columns[0].ColumnName.ToString());

            // Header row's second column onwards, 'inputTable's first column taken
            foreach (DataRow inRow in inputTable.Rows)
            {
                string newColName = inRow[0].ToString();
                outputTable.Columns.Add(newColName);
            }

            // Add rows by looping columns      
            for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
            {
                DataRow newRow = outputTable.NewRow();

                // First column is inputTable's Header row's second column
                newRow[0] = inputTable.Columns[rCount].ColumnName.ToString();
                for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
                {
                    string colValue = inputTable.Rows[cCount][rCount].ToString();
                    newRow[cCount + 1] = colValue;
                }
                outputTable.Rows.Add(newRow);
            }

            return outputTable;
        }
        protected DataTable Transpose(DataTable dt)
        {
            DataTable inputTable = dt;

            dt.Columns.Remove("SlNo");
            dt.Columns.Remove("Id#");
            dt.Columns["Stage"].ColumnName = "IndexFields";
            // Table shown in Figure 1.1

            DataTable transposedTable = GenerateTransposedTable(inputTable);
            return transposedTable;

        }

Monday 30 November 2015

Tessnet2 Init-Method crashes with certain tessdata path

The problem is that if you have Tesseract installed there is an environment variable set ( TESSDATA_PREFIX )which contains the path of the tessdata. To use your own path it is necessary to uninstall Tesseract and delete the environment variable.

Wednesday 25 November 2015

Thursday 12 November 2015

Filter DataTable with column value C#



                   string expression;

                    expression = "ControlId = '" + ControlId + "'";

                    DataRow[] foundRows;

                    // Use the Select method to find all rows matching the filter.
                    foundRows = UploadedFiles.Select(expression);
                    if (foundRows.Length > 0)
                      {

                       }

Friday 6 November 2015

Sort DataTable C#



 public static DataTable resort(DataTable dt, string colName, string direction)
        {
            DataTable dtOut = null;
            dt.DefaultView.Sort = colName + " " + direction;
            dtOut = dt.DefaultView.ToTable();
            return dtOut;
        }



  controlsConfig = resort(controlsConfig, "FieldGroup", "ASC");

  public static DataTable Sortbyint(DataTable tdt, string colName, string direction)
        {
            DataTable Ndt = new DataTable();
            DataTable dt = tdt; // Assume this method returns the datatable from service    
            DataTable dt2 = dt.Clone();
            dt2.Columns["SortOrder"].DataType = Type.GetType("System.Int32");

            foreach (DataRow dr in dt.Rows)
            {
                dt2.ImportRow(dr);
            }
            dt2.AcceptChanges();
            DataView dv = dt2.DefaultView;
            dv.Sort = "SortOrder ASC";
            Ndt = dv.ToTable();
            return Ndt;
        }

  controlsConfig = Sortbyint(controlsConfig, "SortOrder", "ASC");

Wednesday 4 November 2015

File access is denied. You do not have the permission required to access the file C:\Outlook\Outlook.pst.

---------------------------
Personal Folders
---------------------------
File access is denied. You do not have the permission required to access the file C:\Outlook\Outlook.pst.
---------------------------
OK  

---------------------------

Solution:- 


1. Locate the pst file that is causing the issue
2. Right click and select Properties
3. Next to "Attributes", make sure "Read-only" is unchecked. 

This is often overlooked but will fix the problem in most cases

Monday 2 November 2015

Windows SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.

solution:-

Disable SmartScreen Filter in Windows 


1. Open Control Panel and click on Action Center icon. Alternatively you can open it by typingAction Center at Start Screen and it'll show it in Settings section of search results page.
2. Now click on "Change Windows SmartScreen settings" link given in left sidebar.

3. It'll open SmartScreen settings window. Now you can select "Don't do anything (turn off Windows SmartScreen)" option and click on OK button.
Windows_8_Smart_Screen.png
4. That's it. It'll immediately turn off SmartScreen feature and you'll no longer get the warning message in Windows 8.
BONUS TIP:
You can also change SmartScreen filter settings using Registry Editor. Just follow these simple steps:
1. Type regedit in RUN or Start search box and press Enter. It'll open Registry Editor.
2. Now go to following key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer
3. In right-side pane, you'll find a string SmartScreenEnabled. Just change its value to any of following:
  • RequireAdmin (To require approval from an administrator before running downloaded unknown software)
  • Prompt (To give user a warning before running downloaded unknown software)
  • Off (To turn off SmartScreen)

Monday 21 September 2015

Create a Div control dynamically in C# Asp.net

Create a Div control dynamically in C# Asp.net 

 System.Web.UI.HtmlControls.HtmlGenericControl Div1 =
      new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");

Thursday 10 September 2015

Get all Table names from my DB in SQL


Get all Table names from my DB in SQL


SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='DB'

Thursday 13 August 2015

Host 'xxxxx' is not allowed to connect to this MySQL server


Failed to Connect to MySQL at 10.10.2.7:3306 with user root

Host 'xxxxx' is not allowed to connect to this MySQL server

connect through Local host  and Run below in the Query window

grant all privileges on . to 'root'@'%' identified by 'password' with grant option;

Tuesday 28 July 2015

DISABLE and ENABLE TRIGGER in SQL

ALTER TABLE "table name" DISABLE TRIGGER  "Trigger Name"

ALTER TABLE  "table name"  ENABLE TRIGGER "Trigger Name"

Wednesday 22 July 2015

Parser Error Message: Authentication to host '' for user '' using method 'mysql_native_password' failed with message: Access denied for user ''@'User' (using password: NO)


Issue:

Parser Error Message: Authentication to host '' for user '' using method 'mysql_native_password' failed with message: Access denied for user ''@'LBSBLRDEVSRV001.lotex.loc' (using password: NO)

Source Error: 


Line 283:    <siteMap>
Line 284:      <providers>
Line 285:        <add name="MySqlSiteMapProvider" 
type="MySql.Web.SiteMap.MySqlSiteMapProvider, MySql.Web, 
Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" 
connectionStringName="LocalMySqlServer" applicationName="/" />

Line 286:      </providers>
Line 287:    </siteMap>


--------------------------------------------------------------------------------------------------------------------------



Solution : - 

commented the below  tag in C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\ machine. config


<providers>
<add name="MySqlSiteMapProvider" type="MySql.Web.SiteMap.MySqlSiteMapProvider, MySql.Web, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/"/>
</providers>

Tuesday 21 July 2015

how to Find and remove uncommitted or open transactions in SQL !


Write  DBCC OPENTRAN in the query window and execute

If open  transaction's available   Result will be 


Then

KILL server process ID
Example:  KILL 53 


STRING FUNCTIONS in SQL

Example SQL String Function - ASCII
- Returns the ASCII code value of a keyboard button and the rest etc (@,R,9,*) .
Syntax - ASCII ( character)
SELECT ASCII('a') -- Value = 97
SELECT ASCII('b') -- Value = 98
SELECT ASCII('c') -- Value = 99
SELECT ASCII('A') -- Value = 65
SELECT ASCII('B') -- Value = 66
SELECT ASCII('C') -- Value = 67
SELECT ASCII('1') -- Value = 49
SELECT ASCII('2') -- Value = 50
SELECT ASCII('3') -- Value = 51
SELECT ASCII('4') -- Value = 52
SELECT ASCII('5') -- Value = 53 




Example SQL String Function - SPACE 
-Returns spaces in your SQL query (you can specific the size of space). 
Syntax - SPACE ( integer)
SELECT ('SQL') + SPACE(0) + ('TUTORIALS')
-- Value = SQLTUTORIALS
SELECT ('SQL') + SPACE(1) + ('TUTORIALS')
-- Value = SQL TUTORIALS 




Example SQL String Function - CHARINDEX
-Returns the starting position of a character string.
Syntax - CHARINDEX ( string1, string2 [ , start_location ] ) 
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial') 
-- Value = 27
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 20) 
-- Value = 27
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 30)
-- Value = 0 (Because the index is count from 30 and above)




Example SQL String Function - REPLACE
-Replaces all occurrences of the string2 in the string1 with string3.
Syntax - REPLACE ( 'string1' , 'string2' , 'string3' )
SELECT REPLACE('All Function' , 'All', 'SQL')
-- Value = SQL Function




Example SQL String Function - QUOTENAME
-Returns a Unicode string with the delimiters added to make the input string a valid Microsoft® SQL Server™ delimited identifier.
Syntax - QUOTENAME ( 'string' [ , 'quote_character' ] ) 
SELECT QUOTENAME('Sql[]String')
-- Value = [Sql[]]String]




Example SQL String Function - STUFF
- Deletes a specified length of characters and inserts string at a specified starting index.
Syntax - STUFF ( string1 , startindex , length , string2 ) 
SELECT STUFF('SqlTutorial', 4, 6, 'Function')
-- Value = SqlFunctional
SELECT STUFF('GoodMorning', 5, 3, 'good')
-- Value = Goodgoodning




Example SQL String Function - LEFT
-Returns left part of a string with the specified number of characters.
Syntax - LEFT ( string , integer) 
SELECT LEFT('TravelYourself', 6) 
-- Value = Travel
SELECT LEFT('BeautyCentury',6) 
-- Value = Beauty




Example SQL String Function - RIGHT
-Returns right part of a string with the specified number of characters.
Syntax - RIGHT( string , integer)
SELECT RIGHT('TravelYourself', 6)
-- Value = urself
SELECT RIGHT('BeautyCentury',6)
-- Value = Century




Example SQL String Function - REPLICATE
-Repeats string for a specified number of times.
Syntax - REPLICATE (string, integer)
SELECT REPLICATE('Sql', 2) 
-- Value = SqlSql




Example SQL String Function - SUBSTRING
-Returns part of a string.
Syntax - SUBSTRING ( string, startindex , length )
SELECT SUBSTRING('SQLServer', 4, 3) 
-- Value = Ser




Example SQL String Function - LEN
-Returns number of characters in a string.
Syntax - LEN( string) 
SELECT LEN('SQLServer')
-- Value = 9




Example SQL String Function - REVERSE
-Returns reverse a string.
Syntax - REVERSE( string)
SELECT REVERSE('SQLServer') 
-- Value = revreSLQS




Example SQL String Function - UNICODE
-Returns Unicode standard integer value.
Syntax - UNICODE( char) 
SELECT UNICODE('SqlServer') 
-- Value = 83 (it take first character)
SELECT UNICODE('S')
-- Value = 83




Example SQL String Function - LOWER
-Convert string to lowercase.
Syntax - LOWER( string )
SELECT LOWER('SQLServer') 
-- Value = sqlserver




Example SQL String Function - UPPER
-Convert string to Uppercase.
Syntax - UPPER( string ) 
SELECT UPPER('sqlserver') 
-- Value = SQLSERVER




Example SQL String Function - LTRIM
-Returns a string after removing leading blanks on Left side.
Syntax - LTRIM( string )
SELECT LTRIM(' sqlserver')
-- Value = 'sqlserver' (Remove left side space or blanks)




Example SQL String Function - RTRIM 
-Returns a string after removing leading blanks on Right side.
Syntax - RTRIM( string )
SELECT RTRIM('SqlServer ')
-- Value = 'SqlServer' (Remove right side space or blanks)

Friday 17 July 2015

Bat File To execute SQL _ Scripts ".bat"


@echo off
set USERNAME=sa
set PASSWORD=password
set DB= Database
set SERVER=server


REM setlocal
REM SET SQLCMD=sqlcmd -S<servername\instancename> -d<database name> -E
REM for %%d in (*.sql) do %SQLCMD% -i%%d
REM endlocal


setlocal



SET SQLCMD=sqlcmd /S %SERVER% /U %USERNAME% /P "%PASSWORD%" /d %DB%
for %%d in (Tables\*.sql) do %SQLCMD% -i%%d -o%%d.log

SET SQLCMD=sqlcmd /S %SERVER% /U %USERNAME% /P "%PASSWORD%" /d %DB%
for %%d in (Data\*.sql) do %SQLCMD% -i%%d -o%%d.log

SET SQLCMD=sqlcmd /S %SERVER% /U %USERNAME% /P "%PASSWORD%" /d %DB%
for %%d in (SP\*.sql) do %SQLCMD% -i%%d -o%%d.log



endlocal


Pause

Thursday 16 July 2015

Date Formatting in C#

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime

SQL Date Format !


Tuesday 7 July 2015

Recover unsaved SQL query scripts

 Use <your database>
SELECT execquery.last_execution_time AS [Date Time], execsql.text AS [Script] FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
where execsql.text like '% something you remember or commd this where condition %'
ORDER BY execquery.last_execution_time DESC

Friday 26 June 2015

Install//UnInstall Windows Service bat file


--------------------------------------
Install Windows Service bat file
--------------------------------------
//Notes put his bat file in same folder and run as a admin
CD\
CD C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319


InstallUtil.exe "%~dp0WindowsService.exe"

pause

--------------------------------------
UnInstall Windows Service bat file
--------------------------------------
//Notes put his bat file in same folder and run as a admin
CD\
CD C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

InstallUtil.exe /u "%~dp0WindowsService.exe"

pause


How To filter distinct Values from a Datatable in C#

   DataView view = new DataView(table);
   DataTable distinctValues = view.ToTable(true, "id");

Tuesday 23 June 2015

SP to Generate Random Password in SQL (with upper,lower case characters,digits ,punctuation characters)


GO
/****** Object:  StoredProcedure [dbo].[USP_GenerateRandomPassword]    Script Date: 6/23/2015 12:52:26 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Gokuldas.Palapatta
-- Create date: 19th feb 20114
--/* Description: Should contain both upper and lower case characters
--(e.g., a-z, A-Z), digits and punctuation characters as well as
-- letters e.g., 0-9, !@#$%^&*()_+|~-=\`{}[]:";'<>?,./) and should be at least
--eight (alphanumeric with one special and one upper case) characters long */
--declare @x varchar(10)
--execute USP_GenerateRandomPassword @Password=@x output
--select @x
-- =============================================
CREATE  PROCEDURE [dbo].[USP_GenerateRandomPassword] (@Password varchar(10)='' OUTPUT)

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @vRandomNum_Var varchar(10)
DECLARE @SPL VARCHAR(2)
SET @vRandomNum_Var = ''

Declare  @TempTable TABLE(
                         ID int,
                         Charachter char(20))
INSERT INTO @TempTable (ID, Charachter)  SELECT 35, '#'
INSERT INTO @TempTable (ID, Charachter)  SELECT 64, '@'
INSERT INTO @TempTable (ID, Charachter)  SELECT 36, '$'
INSERT INTO @TempTable (ID, Charachter)  SELECT 37, '%'
INSERT INTO @TempTable (ID, Charachter)  SELECT 94, '^'
INSERT INTO @TempTable (ID, Charachter)  SELECT 38, '&'
INSERT INTO @TempTable (ID, Charachter)  SELECT 42, '*'
INSERT INTO @TempTable (ID, Charachter)  SELECT 95, '_'
INSERT INTO @TempTable (ID, Charachter)  SELECT 45, '-'

  SET @SPL = (SELECT top 1 Charachter FROM @TempTable
ORDER BY NEWID())



SET @vRandomNum_Var = (select top 1 cast((Abs(Checksum(NewId()))%10) as varchar(1)) +
       char(ascii('a')+(Abs(Checksum(NewId()))%25)) +
       char(ascii('A')+(Abs(Checksum(NewId()))%25)) +
  @SPL +
       left(newid(),4)
FROM @TempTable)
SET @vRandomNum_Var = REPLACE(@vRandomNum_Var,' ','')
    SELECT @Password = @vRandomNum_Var

END




Tabular function to split by delimiter in SQL


GO
/****** Object:  UserDefinedFunction [dbo].[FN_SplitStringByDelimiter]    Script Date: 6/23/2015 12:48:47 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select * from dbo.[FN_SplitStringByDelimiter] ('goku,goku1,goku2',',')

CREATE FUNCTION [dbo].[FN_SplitStringByDelimiter]

(

@List VARCHAR(8000),   -- String of values

@SplitOn NVARCHAR(5)    -- delimiter value

)

RETURNS @RtnValue TABLE

(

Id INT IDENTITY(1,1),

Component VARCHAR(50)

)

AS

BEGIN

WHILE (CHARINDEX(@SplitOn,@List)>0)

BEGIN


IF LEN(LTRIM(RTRIM(SUBSTRING(@List,1,CHARINDEX(@SplitOn,@List)-1)))) > 0

INSERT INTO @RtnValue (Component)

SELECT Component = LTRIM(RTRIM(SUBSTRING(@List,1,CHARINDEX(@SplitOn,@List)-1)))

SELECT @List = SUBSTRING(@List, CHARINDEX(@SplitOn,@List)+LEN(@SplitOn),LEN(@list))

END


IF LEN(LTRIM(RTRIM(@List))) > 0
INSERT INTO @RtnValue (Component)
SELECT Component = LTRIM(RTRIM(@List))

-- Delete StringEmpty and NULL values from List
DELETE FROM @RtnValue WHERE Component is null OR Component=''

RETURN

END

Friday 19 June 2015

Sent mail..

-------------------------------------------------------------------------------------------------------------------------
Mail helper class
-------------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Web;


    public class MailHelper
    {
        /// <summary>
        /// This helper class sends an email message using the System.Net.Mail namespace
        /// </summary>
        /// <param name="fromEmail">Sender email address</param>
        /// <param name="toEmail">Recipient email address</param>
        /// <param name="bcc">Blind carbon copy email address</param>
        /// <param name="cc">Carbon copy email address</param>
        /// <param name="subject">Subject of the email message</param>
        /// <param name="body">Body of the email message</param>
        /// <param name="attachment">File to attach</param>

        #region Static Members

        public static void SendMailMessage(string toEmail, string fromEmail, string bcc, string cc, string subject, string body, List<string> attachmentFullPath)
        {
            //create the MailMessage object
            MailMessage mMailMessage = new MailMessage();

            //set the sender address of the mail message
            if (!string.IsNullOrEmpty(fromEmail))
            {
                mMailMessage.From = new MailAddress(fromEmail);
            }

            //set the recipient address of the mail message
            mMailMessage.To.Add(new MailAddress(toEmail));

            //set the blind carbon copy address
            if (!string.IsNullOrEmpty(bcc))
            {
                mMailMessage.Bcc.Add(new MailAddress(bcc));
            }

            //set the carbon copy address
            if (!string.IsNullOrEmpty(cc))
            {
                mMailMessage.CC.Add(new MailAddress(cc));
            }

            //set the subject of the mail message
            if (!string.IsNullOrEmpty(subject))
            {
                mMailMessage.Subject = "UBH Web Application Notification" ;
            }
            else
            {
                mMailMessage.Subject = subject;
            }
           
            //set the body of the mail message
            mMailMessage.Body = body;

            //set the format of the mail message body
            mMailMessage.IsBodyHtml = false;
         
            //set the priority
            mMailMessage.Priority = MailPriority.Normal;

            //add any attachments from the filesystem
            foreach (var attachmentPath in attachmentFullPath)
            {
                Attachment mailAttachment = new Attachment(attachmentPath);
                mMailMessage.Attachments.Add(mailAttachment);
            }
           
            //create the SmtpClient instance
            SmtpClient mSmtpClient = new SmtpClient();

            //send the mail message
            mSmtpClient.Send(mMailMessage);
        }

        /// <summary>
        /// Determines whether an email address is valid.
        /// </summary>
        /// <param name="emailAddress">The email address to validate.</param>
        /// <returns>
        /// <c>true</c> if the email address is valid; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsValidEmailAddress(string emailAddress)
        {
            // An empty or null string is not valid
            if (String.IsNullOrEmpty(emailAddress))
            {
                return (false);
            }

            // Regular expression to match valid email address
            string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            // Match the email address using a regular expression
            Regex re = new Regex(emailRegex);
            if (re.IsMatch(emailAddress))
                return (true);
            else
                return (false);
        }

        #endregion
    }





-------------------------------------------------------------------------------------------------------------------------
Code behind
-------------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Data;

namespace MailSentCracker
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void btnsent_Click(object sender, RoutedEventArgs e)
        {
            bool status = true;

            status = Sendmail();
            if (status == true)
            {
                MessageBox.Show("Sent Succesfully! Life ginga lala.. he he..");

            }
            else
            {
                MessageBox.Show("Some thing gone wrong or Fill the Required fileds (from,to message body)");
            }
        }

        public bool Sendmail()
        {
            bool status = false;
     
         
            try
            {

           
                {

                 
                    string messageBody = txtbody.Text.Length > 1 ? txtbody.Text.ToString() : "";
                    string From = txtfrom.Text.Length > 1 ? txtfrom.Text.ToString() : "";
                    string To = txtTO.Text.Length > 1 ? txtTO.Text.ToString() : "";
                    string cc = txtCC.Text.Length > 1 ? txtCC.Text.ToString() : "";
                    string bcc = txtbcc.Text.Length > 1 ? txtbcc.Text.ToString() : "";
                    string subject = txtsubject.Text.Length > 1 ? txtsubject.Text.ToString() : "";
                    if (messageBody.Length > 1 && From.Length > 1 && To.Length > 1)
                    {
                        MailHelper.SendMail(From, To, bcc, cc, subject, messageBody, "");
                        //MailHelper.SendMail(DefaultEmail, DT.Rows[0]["CanEmail"].ToString(), EmailCC1, DT.Rows[0]["LogUserEmail"].ToString(), "Offer Letter", messageBody, filename);
                        // MailHelper.SendMail(, txt, EmailCC1, DT.Rows[0]["LogUserEmail"].ToString(), "Offer Letter", messageBody);
                        status = true;
                    }
                    else
                    {
                        status = false;
                     

                    }
                }



            }
            catch (Exception ex)
            {
                status = false;

            }
            finally
            {
               
            }
            return status;
        }
    }
}

--------------------------------------------------------------------------------------------------------------
app config
--------------------------------------------------------------------------------------------------------------
<?xml version="1.0"?>
<configuration>

  <system.net>
    <mailSettings>
      <smtp from="goku@gmail.com">
        <network host="smtpout.secureserver.net" port="45" userName="goku@gmail.com" password="dqdwdqwd"/>
      </smtp>
     
    </mailSettings>
  </system.net>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

Sunday 31 May 2015

Storing & Retrieving Dataset from Viewstate

Storing 
 Viewstate["datasetname"] = ds;
For Retrieving 
 ds = (Dataset) Viewstate["datasetname"];

Control 'MainContent_GridView1' of type 'GridView' must be placed inside a form tag with runat=server

public override void VerifyRenderingInServerForm(Control control)
{
   //
}

tell the compiler that the control is rendered explicitly by overriding the VerifyRenderingInServerForm event.

Wednesday 20 May 2015

bat file to run multiple Skype account if one is already open

For 32-bit operating systems:

CD\
CD C:\Program Files\Skype\Phone\

Skype.exe /secondary

For 64-bit operating systems:

CD\
CD C:\Program Files (x86)\Skype\Phone\

Skype.exe /secondary  

Tuesday 12 May 2015

Class for Extracting Each Images from a Pdf file using PDF sharp.!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
//using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System.Text;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Advanced;


namespace OfficeConverter
{
    public class Pdf2Image
    {
        //http://www.pdfsharp.net/wiki/ExportImages-sample.ashx?Code=1
        // Retrive PageCount of a multi-page tiff image
        // Fuction will accept pdf file with full path and split the file in to
        //individual files as per pages and create a folder i folder name.


        public int ExtractPagestoJpeg(string sourcePdfPath, string DestinationFolder)
        {

            int i = 0;
            string filename = sourcePdfPath;


            PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open(filename);



            int imageCount = 0;

            // Iterate pages

            foreach (PdfPage page in document.Pages)
            {

                // Get resources dictionary

                PdfDictionary resources = page.Elements.GetDictionary("/Resources");

                if (resources != null)
                {

                    // Get external objects dictionary

                    PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");

                    if (xObjects != null)
                    {
                        ICollection<PdfSharp.Pdf.PdfItem> items = xObjects.Elements.Values;

                        // Iterate references to external objects
                        int z = 0;
                        foreach (PdfItem item in items)
                        {
                            z = 1;
                            PdfReference reference = item as PdfReference;

                            if (reference != null)
                            {

                                PdfDictionary xObject = reference.Value as PdfDictionary;

                                // Is external object an image?

                                if (xObject != null && xObject.Elements.GetString("/Subtype") == "/Image")
                                {

                                    ExportImage(xObject, ref imageCount, DestinationFolder, z);
                                    z++;
                                }

                            }

                        }

                    }

                }

            }
            return i;

        }

        static void ExportImage(PdfDictionary image, ref int count, string DestinationFolder, int z)
        {

            string filter = image.Elements.GetName("/Filter");

            switch (filter)
            {

                case "/DCTDecode":

                    ExportJpegImage(image, ref count, DestinationFolder, z);

                    break;



                case "/FlateDecode":
                    ExportAsPngImage(image, ref count);


                    break;

            }

        }

        static void ExportJpegImage(PdfDictionary image, ref int count, string DestinationFolder, int z)
        {

            // Fortunately JPEG has native support in PDF and exporting an image is just writing the stream to a file.

            byte[] stream = image.Stream.Value;


            FileStream fs = new FileStream(String.Format(DestinationFolder + "//" + z + ".jpeg", count++), FileMode.Create, FileAccess.Write);

            BinaryWriter bw = new BinaryWriter(fs);

            bw.Write(stream);

            bw.Close();

        }

        static void ExportAsPngImage(PdfDictionary image, ref int count)
        {

            int width = image.Elements.GetInteger(PdfImage.Keys.Width);

            int height = image.Elements.GetInteger(PdfImage.Keys.Height);

            int bitsPerComponent = image.Elements.GetInteger(PdfImage.Keys.BitsPerComponent);


            // TODO: You can put the code here that converts vom PDF internal image format to a Windows bitmap

            // and use GDI+ to save it in PNG format.

            // It is the work of a day or two for the most important formats. Take a look at the file

            // PdfSharp.Pdf.Advanced/PdfImage.cs to see how we create the PDF image formats.

            // We don't need that feature at the moment and therefore will not implement it.

            // If you write the code for exporting images I would be pleased to publish it in a future release

            // of PDFsharp.

        }
    }
}