Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for the ‘asp.net feature’ Category

String.Split – by Multiple Character Delimiter in C#.Net

Posted by Viral Sarvaiya on October 31, 2012


 

Basically String Split function split the string with the single character delimiter;
we take one example of single string of the multiple emails.
If we have comma separated emails then we can use Split function as like below

string strEmailText = "abc.abc@yahoo.com,xyz.xyz@gmail.com,some.text@yahoo.co.in";
string[] strSplitText = strEmailText.Split(",");

this will give us string array of the Emails.

But what if we want to use split with 2 or more than one character?
Means what if i have string as like below

string strEmailText = "abc.abc@yahoo.com,xyz.xyz@gmail.com;some.text@yahoo.co.in,pqr.xyz@msn.com";

at this time above split function will not work with this string. so for that below solution works well.

string strEmailText = "abc.abc@yahoo.com,xyz.xyz@gmail.com;some.text@yahoo.co.in,pqr.xyz@msn.com";
string[] strSplitText = strEmailText.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

this will give you string array of the Emails.

Thanks.

Posted in .Net, ASP.NET, asp.net feature, LINQ | Tagged: , , , , , , , , , | Leave a Comment »

Difference Between LINQ to SQL and Entity Framework

Posted by Viral Sarvaiya on August 14, 2012


In my current company we have discussion about what is the difference between LINQ to SQL Vs Entity Framework and I get following conclusion from the surfing from internet (off course from google. 🙂 )

LINQ to SQL supports one to one mapping of database table or views or procedures or functions
Entity Framework map single class to multiple tables of database. Means you can map one table to multiple entities or multiple table to one entities.

LINQ to SQL does not support the creation of complex types
Entity Framework support the creation of complex types.

LINQ to SQL is easy to use
Entity framework is more complex compared to LINQ to SQL.

While introduction of LINQ to SQL it supports only sql server and letter on “DBLINQ” that can use with mysql, sqllite or other DBs
Entity Framework  plug with any database server like DB2, Sybase, Oracle, SQL Azure and other.

In LINQ to SQL, inheritance is difficult.
Entity Framework is simple to apply because it supports Table per class and table per Type.

LINQ to SQL file type is DBML
Entity Framework File type is EDMX.

LINQ to SQL has DataContext object which we can query the database,
Entity Framework, we can query database using LINQ To Entities through the ObjectContext object and ESQL(provides SQL like query language). In addition, Entity Framework has ObjectQuery class(used with Object Services for dynamically constructing queries at runtime) and EntityClient provider(runs query against conceptual model).

LINQ to SQL is slow for the first time run, after first run acceptable performance.
Entity Framework is also slow for the first but  performance is good then LINQ to SQL after first run.

LINQ to SQL has not capability to generate database from Model
Entity Framework has capability to generate database from Model.

Thanks.

Posted in .Net, ASP.NET, asp.net feature, LINQ | Tagged: , , , , , | Leave a Comment »

LINQ: Compare two Sequences

Posted by Viral Sarvaiya on April 4, 2012


Today i get very good and very simple way to compare two arrays.

.Net provide very simple way to compare sequences with Enumerable.SequenceEqual()

Function SequenceEqual() compare target and source sequence and return Boolean value, so we  can know that sequence is similar or not.

for ex.

var ar1 = new[] {1, 2, 3, 4, 5, 6, 7 };
var ar2 = new[] {1, 3, 4, 6 };

var result = ar1.SequenceEqual(ar2);

Console.WriteLine(Result.ToString());

Result : False

Now we want to get that element that is different, for that LINQ gives us best function Except() which works as like below.

if(!result)
{
var differ = ar1.Except(ar2);
Array.ForEach(differ.ToArray(), a => Console.WriteLine(a));
}

Out Put:
2
5
7

Hope this will helps you,
Thanks.

Posted in .Net, ASP.NET, asp.net feature, LINQ | Tagged: , , , , , , , | 4 Comments »

Send Email Attachment Using A Memory Stream

Posted by Viral Sarvaiya on December 12, 2011


mainly we send attachment as a file which is already in the server, but from memory stream we can also send as a attachment in email, below is code for that,


Dim strMailServer As String = "SMTPServerName"

Dim fs As New FileStream("FilePath\FileName.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

Dim sReader As New StreamReader(fs)

Dim objMemoryStream As New MemoryStream()

Dim sb As New System.Text.StringBuilder("")
Dim str As String

'--read through template form, replace variables and add lines to string builder

Do While sReader.Peek() >= 0

str = sReader.ReadLine()

'--replace [Date_Time]
'Replace string here

sb.Append(str)

Loop

Dim Encoding As New UTF8Encoding

Dim arrByt() As Byte = Encoding.GetBytes(sb.ToString())

objMemoryStream.Write(arrByt, 0, arrByt.Length)

objMemoryStream.Position = 0

'--release file system resources

sReader.Close()

sReader.Dispose()

fs.Close()

fs.Dispose()

Dim objMailMessage As New MailMessage

Dim objSMTP As New SmtpClient

Dim toAddress As New MailAddress("ToEmailAddress", "ToEmailName")

objMailMessage.To.Add(toAddress)

Dim fromAddress As New MailAddress("FromEmailAddress", "FromEmailName")

objMailMessage.From = fromAddress

objMailMessage.IsBodyHtml = False
objMailMessage.Priority = MailPriority.Normal

objMailMessage.Subject = "EmailSubject"

objMailMessage.Body = "Email Body"

' add fax cover page as first file attachment

objMailMessage.Attachments.Add(New Attachment(objMemoryStream, "FileName.txt"))

Try

objSMTP.Host = strMailServer

objSMTP.Send(objMailMessage)

Catch ex As Exception

Throw ex

End Try
<pre>

Enjoy…

Posted in ASP.NET, asp.net feature | Tagged: , , , , , | Leave a Comment »

Monitoring the File System

Posted by Viral Sarvaiya on September 20, 2011


Today i get new thing in my project that use FileSystemWatcher Class, so here i explain how to monitoring the file system,

You can use the FileSystemWatcher class (part of the System.IO namespace) to respond to updated files, new files, renamed files, and other updates to the file system. First, create an instance of FileSystemWatcher by providing the path to be monitored. Then, configure roperties of the FileSystemWatcher instance to control whether to monitor subdirectories and which types of changes to monitor. Next, add a method as an event handler. Finally, set the FileSystemWatcher.EnableRaisingEvent property to true. The following code sample demonstrates a basic usage.

// Create an instance of FileSystemWatcher
FileSystemWatcher fsw = new FileSystemWatcher(Environment.GetEnvironmentVariable("USERPROFILE"));
// Set the FileSystemWatcher properties
fsw.IncludeSubdirectories = true;
fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
// Add the Changed event handler
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
// Start monitoring events
fsw.EnableRaisingEvents = true;

Handling FileSystemWatcher Events When a file is changed that meets the criteria you specify, the CLR calls the FileSystemWatcher.Changed event handler for all changes, creations, and deletions. For files and folders that are renamed, the CLR calls the FileSystemWatcher.Renamed event handler. The previous code sample added the fsw_Changed method to handle the Changed event. The following code sample shows a simple way to handle the event:


static void fsw_Changed(object sender, FileSystemEventArgs e)
{
// Write the path of a changed file to the console
Console.WriteLine(e.ChangeType + ": " + e.FullPath);
}

You can use a single event handler for the Changed, Created, and Deleted events. The FileSystemEventArgs parameter provides the path to the updated file and the type of change that occurred. If you need to respond to files that are renamed, you need to create an event handler that accepts a RenamedEventArgs parameter instead of a FileSystemEventArgs parameter, as the following code sample demonstrates:


static void fsw_Renamed(object sender, RenamedEventArgs e)
{
// Write the path of a changed file to the console
Console.WriteLine(e.ChangeType + " from " + e.OldFullPath + " to " + e.Name);
}

Configuring : FileSystemWatcher Properties You can configure the following properties of the FileSystemWatcher class to control which types of updates cause the CLR to throw the Changed event:

Filter : Used to configure the filenames that trigger events. To watch for changes in all files, set the Filter property to an empty string (“”) or use wildcards (“*.*”). To watch a specific file, set the Filter property to the filename. For example, to watch for changes in the file MyDoc.txt, set the Filter property to “MyDoc.txt”. You can also watch for changes in a certain type of file. For example, to watch for changes in text files, set the Filter property to “*.txt”.

NotifyFilter Configure the types of changes for which to throw events by setting NotifyFilter to one or more of these values:

  • FileName
  • DirectoryName
  • Attributes
  • Size
  • LastWrite
  • LastAccess
  • CreationTime
  • Security

Path : Used to define the folder to be monitored. You can define the path using the FileSystemWatcher constructor. You can watch for the renaming, deletion, or creation of files or directories. For example, to watch for the renaming of text files, set the Filter property to “*.txt” and call the WaitForChanged method with a Renamed value specified for its parameter.

Posted in .Net, ASP.NET, asp.net feature | Tagged: , , , , , , , | Leave a Comment »

NHibernate for .NET

Posted by Viral Sarvaiya on September 5, 2011


Recently I have do some work in new technology – NHibernate.

NHibernate is same as JAVA’s Hibernate Core in .net framework. NHibernate is object-relational mappers(ORM). It handles persisting plain .NET objects to and from an underlying relational database. with an XML description of your entities and relationships, NHibernate automatically generates SQL for the objects.Persistent classes do not need to implement any interface or inherit from a special base class. This makes it possible to design the business logic using plain .NET (CLR) objects and object-oriented idiom.

NHibernate key features:

Natural programming model – NHibernate supports natural OO idiom; inheritance, polymorphism, composition and the .NET collections framework, including generic collections.

Native .NET – NHibernate API uses .NET conventions and idioms

Support for fine-grained object models – a rich variety of mappings for collections and dependent objects

No build-time bytecode enhancement – there’s no extra code generation or bytecode processing steps in your build procedure

The query options – NHibernate addresses both sides of the problem; not only how to get objects into the database, but also how to get them out again

Custom SQL – specify the exact SQL that NHibernate should use to persist your objects. Stored procedures are supported on Microsoft SQL Server.

Support for “conversations” – NHibernate supports long-lived persistence contexts, detach/reattach of objects, and takes care of optimistic locking automatically

Free/open source – NHibernate is licensed under the LGPL (Lesser GNU Public License)

 

For More details :

http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx

http://nhforge.org/wikis/howtonh/your-first-nhibernate-based-application.aspx

Posted in .Net, asp.net feature | Tagged: , , , , | Leave a Comment »

Interop type cannot be embedded. Use the applicable interface instead

Posted by Viral Sarvaiya on August 2, 2011


Today i face one more difficulty in my current project,

i am useing .net 4.0 framework with WPF application.

In this application i am adding one dll file that communicate with COM port and i get error “Interop type cannot be embedded. Use the applicable interface instead.”.

this code is perfactly run with .net 3.5 framework but not in 4.0.

and i get the solution for that as below.

Common Language Runtime in .Net 4.0 supports embedding of COM types information directly into managed assemblies in order to simplify deployment process. Managed assemblies need not have to read type information from interop assemblies any more.

In the managed assembly  you can embaded only COM type metadata so it will only works with interfaces, structures, enums and delegates

so what to do for this problem? the solution is “use interfaces instead of classes” or “simply copy constant values from the class definition locally and use them instead.”

hope this will helps you..

thanks

Posted in .Net, asp.net feature | Tagged: , , , , , | 5 Comments »

Check printer status in .net

Posted by Viral Sarvaiya on August 1, 2011


Hi

Today i get new thing from my current projet, how to check the status of the printer means wether the printer is connected to PC or not.

For that we have to add reference of the “System.Management”

Here it is code for check status of the printer.


using System.Management;

class PrinterOffline
{
private static void Main(string[] args)
{
// Set management scope
ManagementScope scope = new ManagementScope("\\root\\cimv2");
scope.Connect();
// Select Printers from WMI Object Collections
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
string printerName = "";
foreach (ManagementObject printer in searcher.Get()) {
printerName = printer("Name").ToString().ToLower();
if (printerName.Equals("Name_Of_Printer")) {
Console.WriteLine("Printer = " + printer("Name"));
if (printer("WorkOffline").ToString().ToLower().Equals("true")) {
// printer is offline by user
Console.WriteLine("Your Plug-N-Play printer is not connected.");
} else {
// printer is not offline
Console.WriteLine("Your Plug-N-Play printer is connected.");
}
}
}
}
}

 

thanks and enjoy coding…

Posted in .Net, ASP.NET, asp.net feature, Visual Studio, WPF | Tagged: , , , , , , , | 6 Comments »

Understanding the Dynamic Keyword in C# 4

Posted by Viral Sarvaiya on June 13, 2011


The dynamic keyword and the Dynamic Language Runtime (DLR) are major new features in C# 4 and the Microsoft .NET Framework 4. These features generated a lot of interest when announced—along with a lot of questions. There were a number of answers as well, but they’re now spread throughout documentation and on various technical blogs and articles. So people continue asking the same questions again and again on forums and at conferences.

This article provides a general overview of the new dynamic features in C# 4 and also delves into some more in-depth information about how they work with other language and framework features, such as reflection or implicitly typed variables. Given there’s a lot of information available already, I’ll sometimes reuse classic examples with links to the original sources. I’ll also provide plenty of links for further reading.

For More Details Click Here

Posted in .Net, asp.net feature | Tagged: , , , , , | Leave a Comment »

DataTable to CSV File and CSV file to Dataset in asp.net

Posted by Viral Sarvaiya on April 21, 2011


Hi,

here i give you 2 simple function for the export Datatable/Dataset to CSV file format and import CSV file to dataset/DataTable.

1. DataTable/DataSet to CSV file

private void DataTableToCSVFile(string filename)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in dtExcelUpdown.Columns)
{
context.Response.Write(column.ColumnName + ",");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in dtExcelUpdown.Rows)
{
for (int i = 0; i < dtExcelUpdown.Columns.Count; i++)
{
context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
context.Response.End();
}

2. CSV file to DataSet/DataTable

from the upload control you have to save to directory and then this path and file name give as a parameter of the function.


private DataSet GetCVSFile(string pathName, string fileName)
{
OleDbConnection ExcelConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties=Text;");
OleDbCommand ExcelCommand = new OleDbCommand(@"SELECT * FROM " + fileName, ExcelConnection);

OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);

ExcelConnection.Open();

DataSet ExcelDataSet = new DataSet();
ExcelAdapter.Fill(ExcelDataSet);

ExcelConnection.Close();
return ExcelDataSet;
}

thanks…

enjoy coding…..

Posted in .Net, ASP.NET, asp.net feature | Tagged: , , , , , , , , | Leave a Comment »

 
%d bloggers like this: