Code Simplified – Viral Sarvaiya

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

Archive for the ‘ASP.NET’ Category

Posts that are related to the ASP.NET controls and features

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 »

Random in Linq

Posted by Viral Sarvaiya on July 12, 2012


In sql query if we want to get one random row form the whole set of data we get from NEWID() in select statement’s order by clouse as like below.

Select top 1 * from Customers where IsActive = 1 order by newid()

What if we are using ORM like linq?

We can do this at the database, by using a fake UDF; in a partial class, add a method to the data context

partial class MyDataContext {
    [Function(Name="NEWID", IsComposable=true)]
    public Guid Random()
    { // to prove not used by our C# code...
        throw new NotImplementedException();
    }
 }

Then just order by ctx.Random(); this will do a random ordering at the SQL-Server courtesy of NEWID(). i.e.

var cust = (from row in ctx.Customers
   .where row.IsActive // your filter
   .orderby ctx.Random()
   select row).FirstOrDefault();

Note that this is only suitable for small-to-mid-size tables; for huge tables, it will have a performance impact at the server, and it will be more efficient to find the number of rows (Count), then pick one at random (Skip/First).

var qry = from row in ctx.Customers select row;

int count = qry.Count(); // 1st round-trip
int index = new Random().Next(count);

Customer cust = qry.Skip(index).FirstOrDefault(); // 2nd round-trip

We can also do woth Guid class

var cust = ctx.Customers
 .Where(x => x.IsActive)
 .OrderBy(x => Guid.NewGuid())
 .FirstOrDefault();

Hope this will helps you.

Thank you.

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

Generating Random String in C#.

Posted by Viral Sarvaiya on May 14, 2012


.Net provide Random class to generate random number.
Here generating random string.

private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

private string RandomString(int size)
{
char[] buffer = new char[size];

for (int i = 0; i < size; i++)
{
buffer[i] = _chars[_rng.Next(_chars.Length)];
}
return new string(buffer);
}

Thanks.

Posted in .Net, ASP.NET | Tagged: , , , | 2 Comments »

Detect browser F5 / refresh and X / Close in javascript

Posted by Viral Sarvaiya on May 8, 2012


Below javascript is use to detect wether browser is refereshed or closed.

window.onunload = function (e) {
// Firefox || IE
e = e || window.event;
var y = e.pageY || e.clientY;

if (y < 0) {
alert("close");
}
else {
alert("refresh");
}
}

Thanks.

Posted in ASP.NET, Javascript, Silverlight | Tagged: , , , , , | 1 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 »

The “CreateRiaClientFilesTask” task failed unexpectedly

Posted by Viral Sarvaiya on February 14, 2012


Some day ago, when i build my project i get unexpected error.

Error 3 The “CreateRiaClientFilesTask” task failed unexpectedly.
System.Web.HttpException (0×80004005): Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied. —> System.Configuration.ConfigurationErrorsException: Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied. —> System.IO.FileLoadException: Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied……….

Sometime that happen when Visual studio cannot access files. so have to remove Temporary file.

I get simple solution from goggling, just close visual studio and reopen, and if Visual studio has no administrator rights then please right click to visual studio icon and choose “Run as a Administrator”.

Then re-build project and problem solved.

Thanks.

Posted in .Net, ASP.NET, RIA WCF, Silverlight, Visual Studio, WCF Services, WPF | Tagged: , , , , , | 4 Comments »

Prevent Silverlight XAP file from caching in your browser.

Posted by Viral Sarvaiya on January 19, 2012


Sometime when we deploy silverlight project, that happen often that when you run website it run older deploy project. because that comes from the cache,

so clear the cache of the Browser and some time that problem occur also after clearing cache.

so for that we have to force website to download new version of xap file every time when it run.

normally we have tag for XAP file, as like below

<param name="source" value="/ClientBin/SilverApp.xap" />

but we have to download our XAP file new at every run of site.

so there so many option for that.

1) changing the Assembly and File version numbers

2) GUID value for the project

but, here is the simple and best solution for that and then it worked like a charm everytime.

<param name="source" value="/ClientBin/SilverApp.xap?ignoreme=<%=System.DateTime.Now.ToUniversalTime()%>" />

Enjoy,

Posted in .Net, ASP.NET, Silverlight | Tagged: , , , , , , , , , | 1 Comment »

Convert Text in to Image using C#

Posted by Viral Sarvaiya on December 13, 2011


.net provide us very good functionality to Create image from text, here is function that return Bitmap and take string as a parameter.


private Bitmap CreateBitmapImage(string TextImage)
{
Bitmap objBmp = new Bitmap(1, 1);

int Width = 0;

int Height = 0;

// Create the Font object for the image text drawing.

Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);

// Create a graphics object to measure the text's width and height.

Graphics objGraphics = Graphics.FromImage(objBmp);

// This is where the bitmap size is determined.

Width = (int)objGraphics.MeasureString(TextImage, objFont).Width;

Height = (int)objGraphics.MeasureString(TextImage, objFont).Height;

// Create the bmpImage again with the correct size for the text and font.

objBmp = new Bitmap(objBmp, new Size(Width, Height));

// Add the colors to the new bitmap.

objGraphics = Graphics.FromImage(objBmp);

// Set Background color

objGraphics.Clear(Color.White);

objGraphics.SmoothingMode = SmoothingMode.AntiAlias;

objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

objGraphics.DrawString(TextImage, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);

objGraphics.Flush();

return (objBmp);
}

Enjoy….

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

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 »

 
Follow

Get every new post delivered to your Inbox.

Join 44 other followers

%d bloggers like this: