Search My Warehouse

2010-01-29

File word count, whitespace count,Word Matches in C#



load event()
{
string FPath = @"D:\x.docx";
string text = File.ReadAllText(FPath);
MatchWord(FPath,"TestWordTOCount");
}

public void MatchWord(string Fname, string WordToMatch)
{
int count;
StreamReader reader = File.OpenText(Fname);
string contents = reader.ReadToEnd();
MatchCollection matches = Regex.Matches(contents, WordToMatch);
count = matches.Count;
}

static int CountNonSpaceChars(string value)
{
///
/// Counts the number of non-whitespace characters.
/// It closely matches Microsoft Word 2007.
///

/// String you want to count non-whitespaces in.
/// Number of non-whitespace chars.

int result = 0;
foreach (char c in value)
{
if (!char.IsWhiteSpace(c))
{
result++;
}
}
return result;
}

static int CountChars(string value)
{

///
/// Return the number of characters in a string using the same method
/// as Microsoft Word 2007. Sequential spaces are not counted.
///

/// String you want to count chars in.
/// Number of chars in string.


int result = 0;
bool lastWasSpace = false;

foreach (char c in value)
{
if (char.IsWhiteSpace(c))
{
// A.
// Only count sequential spaces one time.
if (lastWasSpace == false)
{
result++;
}
lastWasSpace = true;
}
else
{
// B.
// Count other characters every time.
result++;
lastWasSpace = false;
}
}
return result;
}

2010-01-10

Encoding and Decoding string c#

Encode

public string base64Encode(string data)
{
try
{
byte[] encData_byte = new byte[data.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception e)
{
throw new Exception("Error in base64Encode" + e.Message);
}
}

Decode

public string base64Decode(string data)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();

byte[] todecode_byte = Convert.FromBase64String(data);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
catch (Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}



2010-01-09

model

form.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Configuration;

namespace Text_Categorization
{
public partial class Form1 : Form
{
Funtions f = new Funtions();
string ConnStr = ConfigurationSettings.AppSettings["connect2DB"].ToString();
string PassQuery,Result;
int ResultInt,SplitID;
SqlConnection con = new SqlConnection();

public Form1()
{
InitializeComponent();
}

private void btnSave_Click(object sender, EventArgs e)
{
if (f.ErrProvider_AllFields(errorProvider1, this, "Mandatory") == true)
{
PassQuery = "INSERT INTO USERDETAIL VALUES('" + lblUserID.Text + "','" + txtUn.Text.Replace("'", "''") + "','" + txtPwd.Text.Replace("'", "''") + "','" + txtNickname.Text.Replace("'", "''") + "','" + dateDob.Text + "','" + comGender.SelectedItem.ToString() + "','" + txtAddr.Text.Replace("'", "''") + "','" + txtMob.Text.Replace("'", "''") + "','" + txtMail.Text.Replace("'", "''") + "','"+ comCountry.SelectedItem.ToString() +"',0)";
ResultInt = f.ExecQry(con, ConnStr, PassQuery);
if (ResultInt == 1)
MessageBox.Show("User Registered.");
else
MessageBox.Show("Not User Registered.");
}
}

private void Form1_Load(object sender, EventArgs e)
{
comGender.SelectedIndex = 0;
PassQuery = "SELECT MAX(UID) FROM USERDETAIL";
Result = Convert.ToString(f.GetSingle(con, ConnStr, PassQuery));
lblUserID.Text = "TC" + Convert.ToString(Result.Substring(2, 4));
}
}
}


cs:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;

namespace Text_Categorization
{
class Funtions
{
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
SqlDataReader dr;
DataSet ds;
DataTable dt;
int ResultStatus,Counter;
string ResultStr = "";
object ReturnObj = "";
string errorText;
bool bStatus;

public SqlConnection DBconnect(SqlConnection conn, string Constr)
{
if (conn.State != ConnectionState.Open)
{
conn = new SqlConnection(Constr);
conn.Open();
}
return conn;
}

public int ExecQry(SqlConnection conn,string ConnectStr, string Qry)
{
try
{
cmd = new SqlCommand(Qry, DBconnect(conn, ConnectStr));
return ResultStatus = cmd.ExecuteNonQuery();
}
catch
{
return ResultStatus = 0;
}
finally { conn.Close(); conn.Dispose(); }
}

public object GetSingle(SqlConnection conn, string ConnectStr, string Qry)
{
try
{

cmd = new SqlCommand(Qry, DBconnect(conn, ConnectStr));
return ReturnObj = cmd.ExecuteScalar();
}
catch
{
return ReturnObj;
}
finally { conn.Close(); conn.Dispose(); }
}

public DataTable GetDT(SqlConnection conn, string ConnectStr, string Qry)
{
try
{
da = new SqlDataAdapter(Qry, DBconnect(conn, ConnectStr));
da.Fill(dt);
return dt;
}
catch
{
dt.Clear();
return dt;
}
finally
{
conn.Close();
con.Dispose();
}
}

public bool ErrProvider_Combo(ComboBox ComBx, ErrorProvider errorProvider1, string msg)
{
bStatus = true;
if (ComBx.SelectedIndex == 0)
{
errorProvider1.SetError(ComBx, msg);
bStatus = false;
}
else
errorProvider1.SetError(ComBx, "");
return bStatus;
}

public bool ErrProvider_TextBox(TextBox TxtBX, ErrorProvider errorProvider1, string msg)
{
bool bStatus = true;
if (TxtBX.Text == "")
{
errorProvider1.SetError(TxtBX, msg);
bStatus = false;
}
else
errorProvider1.SetError(TxtBX, "");
return bStatus;
}

public bool ErrProvider_AllFields(ErrorProvider errorProvider1, Form ctr,string ErrMsg)
{
Counter=0;
bStatus=true;
foreach (Control ctrl in ctr.Controls)
{
if (ctrl.Text == "")
{
errorProvider1.SetError(ctrl, ErrMsg);
Counter++;
}
}
if (Counter != 0)
return bStatus = false;
else
return bStatus = true;
}

}
}



2010-01-08

Load Image using Ajax C# and VB.net



Create a Empty Page as

ImagePrev.aspx

And Create a new page with the below code:


<div>
<asp:ScriptManager id="ScriptManager1" runat="server">
</asp:ScriptManager><br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Image id="Image1" runat="server"></asp:Image>
<br />
<div id="ImagePreviewer" runat="server" style="background-position: center center;
background-image: url(Images/no-image.gif); width: 150px; background-repeat: no-repeat;
height: 150px">
</div>
<asp:FileUpload id="FileUpload1" runat="server"></asp:FileUpload>
<br />
<asp:LinkButton id="lnk_viewImg" runat="server" OnClick="lnk_viewImg_Click">View Image</asp:LinkButton>
<br />
</ContentTemplate>

</asp:UpdatePanel>

</div>


ImagePrev.aspx.cs

protected void lnk_viewImg_Click(object sender, EventArgs e)
{
//Image1.ImageUrl = FileUpload1.

Stream stream = default(Stream);

//HttpPostedFile oFile = Request.Files(0);
HttpPostedFile oFile = Request.Files[0];

stream = oFile.InputStream;

byte[] uploadedFile = new byte[stream.Length + 1];
byte[] a = null;

stream.Read(uploadedFile, 0, Convert.ToInt32(stream.Length));

if (Session["UploadImage"] != null)
Session["UploadImage"] = uploadedFile;
else
Session.Add("UploadImage", uploadedFile);

//ImagePreviewer.Style.Item("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)";
//ImagePreviewer.Style.Add("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)";
ImagePreviewer.Style.Add("BACKGROUND-IMAGE", "url(ImagePrev.aspx)");

}

ImagePrev.aspx.vb

button click

' Create a stream object.
Dim stream As IO.Stream
' Get the file that was selected.
Dim oFile As HttpPostedFile = Request.Files(0)
' Place the file into the stream.
stream = oFile.InputStream
' Create a byte array for the image.
Dim uploadedFile(stream.Length) As Byte
Dim a() As Byte
' Store the image into the byte array.
stream.Read(uploadedFile, 0, stream.Length)
' Store the byte array into a session variable.
If Session.Item("UploadImage") IsNot Nothing Then
Session.Item("UploadImage") = uploadedFile
Else
Session.Add("UploadImage", uploadedFile)
End If

' Set the ImagePreviewer's url to the ImagePrev page.
'ImagePreviewer.Style.Value("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)"
Me.ImagePreviewer.Style.Item("BACKGROUND-IMAGE") = "url(ImagePrev.aspx)"




view image





2010-01-01

save imges in folder. resizing images asp.net c#

resizing images using Class

public class ImageManipulator
{
public Bitmap ScaleByPercent(System.Drawing.Image imgPhoto, int Percent)
{
float nPercent = ((float)Percent / 100);

int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;

int destX = 0;
int destY = 0;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
//bmPhoto.SetResolution(imgPhoto.HorizontalResolution,imgPhoto.VerticalResolution);
bmPhoto.SetResolution(72, 72);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);

grPhoto.Dispose();
return bmPhoto;
}

public bool ThumbnailCallback()
{
return true;
}
}


Upload Images in folder

page load:

profileImageFolderPath = Server.MapPath("ProfileImages");

private void UploadPhoto()
{
Bitmap bitmap = new Bitmap(FileUpload1.FileContent);
float percent = 100;
if (bitmap.Width > bitmap.Height)
{
if (bitmap.Width > 500)
{
float width = (float)bitmap.Width / 500;
percent = percent / width;
}
}
else
{
if (bitmap.Height > 500)
{
float heigth = (float)bitmap.Height / 500;
percent = percent / heigth;
}
}
ImageManipulator imageManipulator = new ImageManipulator();
System.Drawing.Image image = imageManipulator.ScaleByPercent(bitmap, (int)percent);
string imagePath = profileImageFolderPath + "\\" + txtEmail.Text.Trim() + ".jpg";
image.Save(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}





Feed