Thursday, September 13, 2012

Re size image or Generate Thumbnail in asp.net

Code for  re size image in asp.net, It also maintain the aspect ratio and image quality.

private void GenerateThumbnail(byte[] byteArray, int thumbnailSize)
        {
            // Convert byte array into stream
            Stream fStream = new MemoryStream(byteArray);
            Bitmap photo = new Bitmap(fStream);
            // maintain aspect ratio
            int width, height;
            if (photo.Width > photo.Height)
            {
                width = thumbnailSize;
                height = photo.Height * thumbnailSize / photo.Width;
            }
            else
            {
                width = photo.Width * thumbnailSize / photo.Height;
                height = thumbnailSize;
            }

            Size resizeImageSize = new Size(width, height);

            System.Drawing.Image img = System.Drawing.Image.FromStream(fStream);
            System.Drawing.Image thumbnailImage = img.GetThumbnailImage(resizeImageSize.Width, resizeImageSize.Height, null, IntPtr.Zero);

            // use high quality conversion
            using (Graphics graphic = Graphics.FromImage(thumbnailImage))
            {
                graphic.CompositingQuality = CompositingQuality.HighQuality;
                graphic.SmoothingMode = SmoothingMode.HighQuality;
                graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;


                Rectangle rect = new Rectangle(0, 0, resizeImageSize.Width, resizeImageSize.Height);
                graphic.DrawImage(thumbnailImage, rect);


                using (MemoryStream imageStream = new MemoryStream())
                {
                    thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    // convert back into byte array
                    byte[] imageContent = new Byte[imageStream.Length];
                    imageStream.Position = 0;
                    imageStream.Read(imageContent, 0, (int)imageStream.Length);
                   
                    context.Response.ContentType = "image/jpeg";
                    context.Response.OutputStream.Write(imageContent, 0, imageContent.Length);


                }
            }
        }


Thursday, August 9, 2012

Image file validation in File upload control ASP.NET




<!-- file Upload Control -->

 <asp:FileUpload ID="fuMainImage" runat="server" />

<!-- Image file validator -->

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="fuMainImage"   ErrorMessage="Invalid Image File (supported file type are .JPEG, .PNG, .GIF) "  ValidationExpression="^([0-9a-zA-Z :\\-_!@$%^&*()])+(.jpg|.JPG|.jpeg|.JPEG|.png|.PNG|.gif|.GIF)$">
</asp:RegularExpressionValidator>

Tuesday, August 7, 2012

Query to know Foreign key (FK) column in your database MSSQL

SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,
fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,
fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id

Query to know Primary key column in your database MSSQL


Query to know Primary key column in your database MSSQL...

SELECT i.name AS IndexName,
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1 order by OBJECT_NAME(ic.OBJECT_ID)

Query to know identity column in your database MSSQL



Query to know identity column in your database MSSQL

select COLUMN_NAME, TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'dbo'
and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 order by TABLE_NAME

Wednesday, April 20, 2011

code for swap Silverlight xap in html


  <script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript">
        var IsLSC = true;
      // function create Object block inside Div tag
        function CreateSilverlightMenuTree(XapPath) {
            var userDetails = "";
            var objectValue = Silverlight.createObject(
                "/ClientBin/" + XapPath,  // source
               null,  // parent element
                "slPlugin",  // id for generated object element
                {
                width: "100%", height: "100%", background: "transparent", windowless: "true",
                version: "5.0.60401.0"
            }, { onError: onCustomError, onLoad: onCustomLoad },
              "userData=" + userDetails,
            "context"    // context helper for onLoad handler.
            );
            var divObj = document.getElementById("silverlightControlHost");
            divObj.innerHTML = objectValue;
        }
        function onCustomError() {
            window.status += " Error in loading window";
        }
        function onCustomLoad() {
            window.status += " Window loaded";
        }
//function  swap between two xap file dynamically 
        function SwitchXap() {
            var paramObj= "";
            if (IsLSC) {
                paramObj = "LSC.xap";
                IsLSC = false;
              }
            else {
                paramObj = "SilverlightNetwork.xap";
                IsLSC = true;
            }
            CreateSilverlightMenuTree(paramObj);
        }
    </script>

</head>
<body>
    <form id="form1" runat="server" style="height:100%">
    <input id="Button1" type="button" value="Swap" onclick="SwitchXap()" />
    <div id="silverlightControlHost">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
 <param id="paramXap" name="source" value="ClientBin/SilverlightNetwork.xap"/>
 <param name="onError" value="onSilverlightError" />
 <param name="background" value="white" />
 <param name="minRuntimeVersion" value="5.0.60401.0" />
 <param name="autoUpgrade" value="true" />

Wednesday, March 2, 2011

Call Scriptable Methods from JavaScript with Silverlight

Here is code snippet  to be written on html page










and here is code snippet to be written on xmal Page code behind

Thursday, December 9, 2010

Creating and merging two Images in C#

//Creating new Image
var bitmap1 = new Bitmap(1, 1);
var font = new Font("Arial", 25);
Graphics graphics = Graphics.FromImage(bitmap1);
int width1 = (int)graphics.MeasureString("hello world this is custome image", font).Width;
int height1 = (int)graphics.MeasureString("hello world this is custome image", font).Height;
bitmap1 = new Bitmap(bitmap1, new Size(width1, height1));
graphics = Graphics.FromImage(bitmap1);
graphics.Clear(Color.Gray);
graphics.DrawString("hello world this is custome image", font, new SolidBrush(Color.DarkGray), 0, 0);
graphics.Flush();

//accessing existing Image
var fileStream = new FileStream(Server.MapPath("//images//sky.jpg"), FileMode.Open);
var bytes1 = new byte[fileStream.Length];
fileStream.Read(bytes1, 0, bytes1.Length);
fileStream.Close();
var bitmap3 = new Bitmap(new MemoryStream(bytes1));

int width = bitmap3.Width;
int height = bitmap3.Height + height1;
var finalImage = new Bitmap(width, height);

//merging two images
//get a graphics object from the image so we can draw on it

var images = new List{bitmap3,bitmap1};
using (graphics = Graphics.FromImage(finalImage))
{
//set background color
graphics.Clear(Color.Transparent);

//go through each image and draw it on the final image
int offset = 0;
foreach (Bitmap image in images)
{
graphics.DrawImage(image,
new Rectangle(0, offset, image.Width, image.Height));
offset += image.Height;
}
}

// save on memory
var memoryStream = new MemoryStream();
finalImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] bytes = memoryStream.ToArray();

// throwing on web
HttpContext.Current.Response.ContentType = "image/jpeg";
HttpContext.Current.Response.Expires = 0;
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.End();

Wednesday, December 8, 2010

Rotate any control in silverlight

Rotate any control in silverlight

var messageTextBlock = new TextBlock
{
Text = "Messages",
Margin = new Thickness(5,20,0,0),
//FontWeight = FontWeights.Bold,
Foreground = new SolidColorBrush(Colors.White),
VerticalAlignment = VerticalAlignment.Top,
Width = 70,
Height=20,
TextWrapping = TextWrapping.Wrap,
};
RotateTransform r = new RotateTransform();
messageTextBlock.RenderTransform = r;
r.CenterX = 0;
r.CenterY = 0;
r.Angle = 90;

Tuesday, August 10, 2010

FluidMoveBehavior


Learn to create applications that change layout and visual appearance using smooth, dynamic and visually rich transitions without writing code. Come see new features in Expression Blend that raise the bar, making it even easier to create amazing applications that will delight users

Tuesday, May 18, 2010

custom drag drop in silverlight

custom drag drop in silverlight
#region custom Drag Drop

double _horizDrag = 0;
double _vertDrag = 0;
double _mouseVerticalPosition;
double _mouseHorizontalPosition;
bool _captured = false;
bool _isDragStart = false;
private void EndDragPopupMouseLeftUp()
{

_horizDrag = _vertDrag = 0;
_captured = false;
popupContent.Content = null;
popupContent.ContentTemplate = null;
//popup1.ReleaseMouseCapture();
_mouseVerticalPosition = -1;
_mouseHorizontalPosition = -1;
var ts = new ThreadStart(DragHold);
// create new thread
var thrd = new Thread(ts);
// start thread
thrd.Start();
}
public void DragHold()
{
// makes the main thread sleep - let sub thread to run
Thread.Sleep(100);
//if (!IsOver)
_isDragStart = false;
}
private void MoveDragPopupMouseMove(MouseEventArgs e)
{
if (_captured)
{

// Calculate the current position of the object.
double deltaV = e.GetPosition(null).Y - _mouseVerticalPosition;
double deltaH = e.GetPosition(null).X - _mouseHorizontalPosition;
_horizDrag += deltaH;
_vertDrag += deltaV;
double newTop = deltaV + (double)popup1.VerticalOffset;
double newLeft = deltaH + (double)popup1.HorizontalOffset;

// Set new position of object.
popup1.VerticalOffset = newTop;
popup1.HorizontalOffset = newLeft;


// Update position global variables.
_mouseVerticalPosition = e.GetPosition(null).Y;
_mouseHorizontalPosition = e.GetPosition(null).X;
var temBor = popupContent.Content as Border;
var lbl = temBor.Child as Label;
lbl.Content = "Selected to Drop (X=" + _mouseVerticalPosition + ",Y=" + _mouseHorizontalPosition + ")";
}
}
private void StartDragMouseLeftDown(MouseEventArgs e,object tag)
{
Thread.Sleep(350);

var myEffect = new DropShadowEffect
{
Color = Colors.Black,
BlurRadius = 5,
Direction = 280,
Opacity = 0.7,
ShadowDepth = 5,
};

var borde = new Border
{
BorderThickness = new Thickness(2),
BorderBrush = new SolidColorBrush(Colors.White),
Effect = myEffect,
Opacity = .7,
Tag = tag,
};
var lbl = new Label
{
Content = "Selected to Drop",
Foreground = new SolidColorBrush(Colors.Blue),
Background = new SolidColorBrush(Colors.DarkGray),
//BorderBrush = new SolidColorBrush(Colors.Orange),
BorderThickness = new Thickness(0)
};

borde.Child = lbl;
popupContent.Content = borde;
//popup1.CaptureMouse();
_captured = true;
_mouseVerticalPosition = e.GetPosition(null).Y;
_mouseHorizontalPosition = e.GetPosition(null).X;
popup1.HorizontalOffset = _mouseHorizontalPosition;
popup1.VerticalOffset = _mouseVerticalPosition;
_isDragStart = true;
}
private void GetDragDropElement()
{
if (_isDragStart)
{
MessageBox.Show("dropd on me");
_isDragStart = false;
}

}
//on .xaml file
/*
*/
#endregion

Tuesday, April 20, 2010

Get parent type Object ex. in treeview

void method
{
// calling the method
TreeViewItem trvItem = GetParentTreeViewItem((DependencyObject)sender);
}
// this will return the desire type exg. here it is returning TreeViewItem type..
private static TreeViewItem GetParentTreeViewItem(DependencyObject item)
{

if (item != null)
{
DependencyObject parent = VisualTreeHelper.GetParent(item);
TreeViewItem parentTreeViewItem = parent as TreeViewItem;
return (parentTreeViewItem != null) ? parentTreeViewItem : GetParentTreeViewItem(parent);
}
return null;

}

Monday, April 12, 2010

Get xml from web services and use in tree view of silver light

private void cmbTaxonomy_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
_objWebService.getTreeOfClassCompleted += new EventHandler(_objWebService_getTreeOfClassCompleted);
_objWebService.getTreeOfClassAsync(cmbTaxonomy.SelectedItem.ToString());
}
const string xmlNodeTextAttName = "Name";
const string xmlNodeTagAttId = "Id";
const string xmlNodeTagClass = "Class";
const string xmlNodeTagRoot = "Root";
void _objWebService_getTreeOfClassCompleted(object sender, getTreeOfClassCompletedEventArgs e)
{
XDocument xDocument = XDocument.Parse(e.Result);
trvHierarchy.Items.Clear();
if (xDocument.Root != null)
if(xDocument.Root.Elements().ToArray().Count()>0)
{
foreach (var VARIABLE in xDocument.Root.Elements().ToArray())
{
if (VARIABLE != null)
{
TreeViewItem parentNodeItem = new TreeViewItem
{
IsExpanded = true,
Header = CreateTreeViewItemHeader(VARIABLE.Attribute(xmlNodeTextAttName).Value, Convert.ToInt64(VARIABLE.Attribute(xmlNodeTagAttId).Value))
};
AddChildItemsInTree(VARIABLE, parentNodeItem);
trvHierarchy.Items.Add(parentNodeItem);
}

}
}
}

private void AddChildItemsInTree(XElement ParentVariable, TreeViewItem parentNodeItem)
{
if(ParentVariable.HasElements)
{
foreach(var variableChild in ParentVariable.Elements().ToArray())
{
if (ParentVariable != null)
{
TreeViewItem childNodeItem = new TreeViewItem
{
IsExpanded = true,
Header = CreateTreeViewItemHeader(variableChild.Attribute(xmlNodeTextAttName).Value, Convert.ToInt64(variableChild.Attribute(xmlNodeTagAttId).Value))
};
//childNodeItem.Header = variableChild.Attribute(xmlNodeTextAttName).Value;
AddChildItemsInTree(variableChild, childNodeItem);
parentNodeItem.Items.Add(childNodeItem);
}
}
}
}

Creat xml for web services and return it

public string getTreeOfClass(string taxonomyName)
{
//get ClassElementsName
var taxsonomyId = _exhibitDb.Taxonomies.SingleOrDefault(o => o.Taxonomy1 == taxonomyName);

var classeList = from c in _exhibitDb.Classes join tc in _exhibitDb.TaxonomyClasses on c.ID equals tc.ClassID where (tc.TaxonomyID.Equals(taxsonomyId.ID)) select c;
//XDocument document = new XDocument();
//document.Root
const string xmlNodeTextAttName = "Name";
const string xmlNodeTagAttId = "Id";
const string xmlNodeTagClass = "Class";
const string xmlNodeTagRoot = "Root";
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true,
NewLineOnAttributes = false,
Encoding = Encoding.UTF8
};
StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb, settings);
//writing xml

if (writer != null)
{
writer.WriteStartDocument();
writer.WriteStartElement(xmlNodeTagRoot);
foreach (var v in classeList)
{
writer.WriteStartElement(xmlNodeTagClass);
writer.WriteAttributeString(xmlNodeTextAttName, v.Class1);
writer.WriteAttributeString(xmlNodeTagAttId, v.ID.ToString());
AddChildElement(writer, v.ID, xmlNodeTagAttId, xmlNodeTextAttName, xmlNodeTagClass);
writer.WriteEndElement();
}

writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
return sb.ToString();// xmlDocument;
}

Friday, July 10, 2009

crrating csv in c# and asp.net

public void getHBRemindercsvFile()
{
if(dsBdayReminder.Tables[0].Rows.Count<1)
{
LblError.Visible=true;
LblError.Text="You have no reminders !";
}
string attachment = "attachment; filename=BirthdayReminder.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
WriteColumnName(" Name , Day , Month ");
foreach (DataRow drt in dsBdayReminder.Tables[0].Rows)
{
WriteHBReminder(drt);
}

HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
private void WriteHBReminder(DataRow drt)
{
StringBuilder stringBuilder = new StringBuilder();

AddComma(drt["reminder_name"].ToString(), stringBuilder);
AddComma(drt["reminder_day"].ToString(), stringBuilder);
AddComma(GetMonthName(Convert.ToInt32(drt["reminder_month"])), stringBuilder);

HttpContext.Current.Response.Write(stringBuilder.ToString());
HttpContext.Current.Response.Write(Environment.NewLine);
}

private void AddComma(string value, StringBuilder stringBuilder)
{
stringBuilder.Append(value.Replace(',', ' '));
stringBuilder.Append(", ");
}

private void WriteColumnName(string columnNames)
{
HttpContext.Current.Response.Write(columnNames);
HttpContext.Current.Response.Write(Environment.NewLine);
}

making thumbnil in asp.net

public class MakeThumbnail : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// get the file name -- fall800.jpg
string file = Request.QueryString["file"];

// create an image object, using the filename we just retrieved
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(file));

// create the actual thumbnail image
System.Drawing.Image thumbnailImage = image.GetThumbnailImage(160, 120, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

// make a memory stream to work with the image bytes
MemoryStream imageStream = new MemoryStream();

// put the image into the memory stream
thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);//Imaging.Imageformat.Jpeg);

// make byte array the same size as the image
byte[] imageContent = new Byte[imageStream.Length];

// rewind the memory stream
imageStream.Position = 0;

// load the byte array with the image
imageStream.Read(imageContent, 0, (int)imageStream.Length);

// return byte array to caller with image type
Response.ContentType = "image/jpeg";
Response.BinaryWrite(imageContent);
}
public bool ThumbnailCallback()
{
return true;
}

HTML tag
img src='wallpaper/MakeThumbnail.aspx?file=<%# DataBinder.Eval(Container.DataItem,"image_path") %>'

Creating Rss in asp.net

private void WriteXmlForRSS(string Id)
{
try
{

getReminderData(Id);
Response.Clear();
Response.ContentType = "text/xml";
XmlTextWriter objX = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
objX.WriteStartDocument();
objX.WriteStartElement("rss");
objX.WriteAttributeString("version","2.0");
objX.WriteStartElement("channel");
objX.WriteElementString("title", "HappyBirthday");
objX.WriteElementString("link","https://www.happybirthday.com/Account/rss.aspx?id="+Id);
objX.WriteElementString("description","The latest birthday's and others reminder from the HappyBirthday.com");
objX.WriteElementString("copyright","(c) 2009, HappyBirthday,com, All rights reserved.");
objX.WriteElementString("ttl","5");
//image
objX.WriteStartElement("image");
objX.WriteElementString("url","https://www.happybirthday.com/home3/logo2.gif");
objX.WriteElementString("title","HappyBirthday");
objX.WriteElementString("link","http://www.happybirthday.com");
objX.WriteEndElement();

//title
objX.WriteStartElement("item");
objX.WriteElementString("title","Birthday Reminders");
//objX.WriteElementString("description","Your Birthday Reminders" );
objX.WriteEndElement();

//Reminders
foreach(DataRow dr in dsBdayReminder.Tables[0].Rows)
{
objX.WriteStartElement("item");
objX.WriteElementString("title",dr["reminder_name"]+"'s birthday ( "+dr["reminder_day"]+" "+GetMonthName(Convert.ToInt32(dr["reminder_month"]))+")");
objX.WriteElementString("category",dr["reminder_month"].ToString());
objX.WriteElementString("description"," "+dr["reminder_name"]+"'s happy birthday is on "+dr["reminder_day"]+ " "+ GetMonthName(Convert.ToInt32(dr["reminder_month"])));
objX.WriteElementString("link","https://www.happybirthday.com/Account/rss.aspx?id="+Id);
objX.WriteElementString("pubDate",DateTime.Now.ToLongDateString());

objX.WriteEndElement();
}
//title
objX.WriteStartElement("item");
objX.WriteElementString("title","Other Reminders");
//objX.WriteElementString("description","Your Other Reminders" );
objX.WriteEndElement();
// other Reminders
foreach(DataRow dr in dsOtherReminder.Tables[0].Rows)
{
objX.WriteStartElement("item");
objX.WriteElementString("title",dr["other_reminder_name"]+"'s "+dr["other_reminder_description"]+" ("+dr["other_reminder_day"]+" "+GetMonthName(Convert.ToInt32(dr["other_reminder_months"]))+")");
objX.WriteElementString("category",dr["other_reminder_months"].ToString());
objX.WriteElementString("description",dr["other_reminder_name"]+"'s "+dr["other_reminder_description"]+" is on "+dr["other_reminder_day"] +" "+GetMonthName(Convert.ToInt32(dr["other_reminder_months"])));
objX.WriteElementString("link","https://www.happybirthday.com/Account/rss.aspx?id="+Id);
objX.WriteElementString("pubDate",DateTime.Now.ToLongDateString());

objX.WriteEndElement();
}


//
objX.WriteEndElement();
objX.WriteEndElement();
objX.WriteEndDocument();
objX.Flush();
objX.Close();

}
catch(Exception ex)
{
Response.Write("Error Occour!");
return;
}
Response.End();
}

html tag


/td vAlign="top" align="center" height="78">

Reminder Feed

Wednesday, July 8, 2009

crating pager in datalist



private void LoadImage(string FolderName)

{

try {

string wallFolderPath = Server.MapPath(FolderName);

string[] FilesColl = Directory.GetFiles(wallFolderPath);

if (FilesColl.Length > 0) {

int tempLength = FilesColl.Length;

for (int i = 0; i < extn =" Path.GetExtension(FilesColl[i]).ToLower();" extn ="=" extn ="=" extn ="=" fs =" new" fn="fs.Name;" fktitle="Path.GetFileName(FilesColl[i]).Replace(extn," drow =" dtWall.NewRow();" imagepath =" FilesColl[i];" imagepath="imagePath.Substring(imagePath.IndexOf(parentImageDir)+parentImageDir.Length+1);" datasource="dtWall.DefaultView;" allowpaging="true;" pagesize =" 16;" currentpageindex =" CurrentPage;" enabled =" !pds.IsLastPage;" enabled =" !pds.IsFirstPage;" datasource="pds;" text="dtWall.Rows.Count.ToString();">0) {




LnlBack.Visible=false;

}

}

catch(Exception ex)

{

ShowError(ex.Message);

}

}




public int CurrentPage

{




get

{

if (this.ViewState["CurrentPage"] == null)

return 0;

else

return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());

}




set

{

this.ViewState["CurrentPage"] = value;

}




}

private void doPaging()

{

DataTable dt = new DataTable();

dt.Columns.Add("PageIndex");

dt.Columns.Add("PageText");

for (int i = 0; i < dr =" dt.NewRow();" datasource =" dt;" currentpage =" Convert.ToInt16(e.CommandArgument.ToString());" wallfoldername =" ViewState[" lnkbtnpage =" (LinkButton)e.Item.FindControl(" enabled =" false;" bold =" true;" wallfoldername =" ViewState[" wallfoldername =" ViewState[">
HTML
asp1:datalist1 id="dlPaging" runatr="serverr" RepeatDirection="Horizontal" Height="15px">

ItemTemplate1>
asp1:LinkButton1 ID="lnkbtnPaging" runatr="serverr" CommandArgument=<# DataBinder.Eval(Container.DataItem,"PageIndex") > CommandName="lnkbtnPaging" Text=<# DataBinder.Eval(Container.DataItem,"PageText") >'> /asp1:LinkButton1 /ItemTemplate1> /asp1:datalist

Wednesday, March 25, 2009

Maximum Date in a group of records

Sort command and groupins i am ok but i need to select only the records that
has the latest enddate


eg-: select h.component_fixed_id ,h.date_added,h.factory_price from history_manufacturer_components as h
where manufacturer_code='arv001' and
date_added =(select max(date_added) from history_manufacturer_components where component_fixed_id=h.component_fixed_id)

or
This query returns row(s) with the latest Enddate for each ID but the row
for ID='B' isn't the one you highlighted.


SELECT id, startdate, enddate
FROM SomeTable AS S
WHERE enddate =
(SELECT MAX(enddate)
FROM SomeTable
WHERE id = S.id)

Wednesday, December 3, 2008

import from excel in c#

private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
path = openFileDialog1.FileName;
}

private void btnImport_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "excel file |*.xls";
openFileDialog1.FilterIndex = 1;
openFileDialog1.InitialDirectory = "%My Documents%";
openFileDialog1.ShowDialog(this);
// path = openFileDialog1.FileName;
if (path != "")
{
try
{
oledbConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + @"; Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""";
olebdConn.ConnectionString = oledbConnectionString;
oledbCmmd.Connection = olebdConn;
oledbCmmd.CommandText = "Select * FROM [Sheet1$]";
olebdConn.Open();
da =new OleDbDataAdapter(oledbCmmd);
da.Fill(ds);

dgvExcelData.Visible = true;
////dt = dr.GetData(4);
int count = ds.Tables[0].Rows.Count;
label2.Text = count.ToString();
////dgvExcelData.Rows.Clear();

dgvExcelData.DataSource = ds.Tables[0];
////dgvExcelData.Visible = true;
olebdConn.Close();
}