Saturday, March 31, 2012

How to save the Image using IHttpHandler in asp.net

The Http process will be used to save the image in database.Here one more class is used to do the data base functionality and The GetUploadBinary method is used to update the image data in data base
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/plain";
if (context.Request.Files.Count == 0)
{
context.Response.Write("No files uploaded.");
return;
}
int id;
if (String.IsNullOrEmpty(context.Request.QueryString["itemId"]) || !Int32.TryParse(context.Request.QueryString["itemId"], out id))
{
context.Response.Write("No item id provided.");
return;
}

TestDataContext tdc = new TestDataContext(Config.ConnectionString);
Orders item = tdc.Orders.FirstOrDefault(p => p.ID.Equals(id));
if (item == null)
{
context.Response.Write("Item not found.");
return;
}
item.Image = SiteUtility.GetUploadBinary(context.Request.Files[0]);
item.ImageType = context.Request.Files[0].ContentType;
tdc.SubmitChanges();
}

Friday, March 30, 2012

Jquery Previous and next month with year

Here i will show how to get the next/previous month with year when we click on the next/previous.For this i will get the current month and current year ,Then when we click on the previous button i will decrease the month to 1 and if year will also decrease one when the month is equal to 0.because if we will not decrease the year when the month index reached 0 ,the previous value of year will be displayed if year is completed
     function Previous() {
                
         if (current_month == 0) {
             current_month = 11;
             current_year = current_year - 1;
         } else {
             current_month = current_month - 1;
         }
         var month = monthNames[current_month];
        $('#testmonth').val=month+','+current_year;
     }
when we click on the next button i will increase the month to 1 and if year will also increase one when the month is equal to 11.because if we will not increase the year when the month index reached 11 ,the previous value of year will be displayed if year is completed
     function Next() {
      
         if (current_month == 11) {
             current_month = 0;
             current_year = current_year + 1;
         } else {
             current_month = current_month + 1;
         }
         var month = monthNames[current_month];
         $('#testmonth').val=month+','+current_year;
}

Thursday, March 29, 2012

get month and year in jquery

Earlier i explained how to Jquery Get next and previous month. Here i will show how to get the current month/Date name from month index using java script. For this i have taken one array variable with month names .Then the result month index will be passed to month names array.Here the resulted month name is assigned to Div using present() function.If we want to get the current year there is an option to get the year i:e getFullYear();
<html>
<head>
<script>
var cdt = new Date();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var current_month = cdt.getMonth();
var month_name = monthNames[current_month];
var current_year =cdt.getFullYear();
     
function present() {
var cdt = new Date();
var month = monthNames[current_month];
var DivObj = document.getElementById('testmonth');
DivObj.innerHTML = month+','+" " + current_year;
}
<script></head>
<body><input type="submit" value="GetMonth" onclick="present()"/>
</body></html>
by using the above function we can get the current date by using Date functionality in jquery
var currentdate = cdt.getDate();

Wednesday, March 28, 2012

Datatable to Gridview in asp.net

Title: How to bind the data to grid view using data table in asp.net c#.net

Description:
Here i will show how to transfer the data the from data table to Grid view .For this i have generated custom data table " dtOrders" and add desired columns to it.Then i created a object to add the row data into data table and expression property is used to get the desirable format of data.

Example:
DataTable dtOrder = new DataTable();
dtOrder.Columns.Add("OrderId"); 
dtOrder.Columns.Add("Name");  
dtOrder.Columns.Add("Quantity");  
dtOrder.Rows.Add(new Object[] { "12", "pharmacy", "2000" });
dtOrder.Columns[3].Expression = string.Format("{0},{1},{2}", "OrderId", "Name", "Quantity"); 
gvOrders.DataSource = dtOrders;    
gvOrders.DataBind();

Tuesday, March 27, 2012

Sharepoint List to gridview in sharepoint 2010

Here i will show how to access the the share point list data to Visual Web part in share point 2010 and the linq query is used to get the data from share point .Then Ive added the below code to web part user control.In can process the the list data to grid view
var Ldc = new SPLinqDataContext(SPContext.Current.Web.Url);
var Orderslist = Ldc.GetList("Orders");
var orederQueryResult = from order in orders where 
order.Dueate < DateTime.Now.AddMonths(6) select new { order.name, order.city, sname = order.name, DueDate =order.Date.Value.ToShortDateString() }; 
spGV.DataSource = orederQueryResult;
spGV.DataBind(); 
The above linq query gets order data based on orderdate
Using DataTable:
<asp:GridView ID="Gvdata" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" />
        <asp:BoundField DataField="Name" />
        <asp:BoundField DataField="DocumnetTYpe" />
        <asp:BoundField DataField="Role" />
        <asp:BoundField DataField="Key" />
    </Columns>
</asp:GridView>


using (SPSite s = new SPSite(url))
{
using (SPWeb sw = s.OpenWeb())
{
SPList sl = sw.Lists["Orders"];
DataTable ResTable = new DataTable();
ResTable.Columns.Add(new DataColumn("Id"));
ResTable.Columns.Add(new DataColumn("Name"));
ResTable.Columns.Add(new DataColumn("DocumentType"));
ResTable.Columns.Add(new DataColumn("Role"));
ResTable.Columns.Add(new DataColumn("Key"));
foreach (SPListItem item in sl.Items)
{
DataRow dr = ResTable.NewRow();
dr["Id"] = item.Id;
dr["Name"] = item.Name;
dr["DocumnetType"] = item.DocumnetType;
dr["Role"] = item.Role;
dr["Key"] = item.Key;
ResTable.Rows.Add(dr);
}
Gvdata.DataSource = ResTable;
Gvdata.DataBind();
}

Monday, March 26, 2012

Jquery Date format

Here i will show a simple way for how to format the date in jquery.Basically all of know the date format can only be done in sql server .But We have number of jquery methods to performs on date objects.In the below script i will get the current date into variable Current date,then it will format into desirable Date format.we can see The which date format has passed to varibale "Dateformat" in below script

var Currentdate = getDate();
var Dateformat = 'dd-MM-yyyy hh:mm:ss';
var DesirableDate =  $.format.date(Currentdate, Dateformat);

The above script gives output like "27-03-2012 07:28:21"

Sunday, March 25, 2012

Jquery How to Select a dropdown selected value

Title:
How to get drop down list selected value using jquery

Description:
When we start working with jquery ,we may think how and where we have to use jquery libraries.Before going to use jquery methods,we should download and add latest version of jquery plugin from jquery.com.With out plug-in we could not use any methods of jquery reference.

Example:
In previous articles i have given Jquery Dropdownlist validation,JqueryUI autocomplete textbox.Jquery Get month or year,Hide and show div using jquery ,Jquery Declare variable.In this post i will show how to get the dropdownlist selected value using jquery.Below script will show  the selected value as alert while page loading

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var ddlOrderText = $("#ddlChar option:selected").text();
alert(ddlOrderText );
var ddlOrderValue = $("#ddlChar option:selected").val();
alert(ddlOrderValue);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlChar" runat="server">
<asp:ListItem>Bhaskar</asp:ListItem>
<asp:ListItem>Aspdotnet</asp:ListItem>
<asp:ListItem>Sharepoint</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>

Thursday, March 22, 2012

How to update the XML file in asp.net

Title:How to read and update XML in asp.net using c#

Description: As per asp.net we have specific number of data source controls.Among these i have used XML data source control for my application.So now i would like to describe and explain about CRUD operations on XML file.As initial we have to get the data source path and read the data from the file .

Example:In the below example we have create a instance for XML document and load  from the specified path.Then i will get the all sales order id's using node list and iterate through the complete document.Mean while we are getting the sales Order customer title and update the name as per data
using System;
using System.Collections.Generic;
using System.Data;
using System.XML;

private void ReadAndUpdateXml_Click(object sender, EventArgs e)
{
XmlDocument newXmldoc= new XmlDocument();
newXmldoc.Load(Server.MapPath("~/XMLFiles/salesOrder.xml"));
XmlNodeList nodeList = newXmldoc.SelectNodes("//Orders/OrderId");
int i = 1;
foreach (XmlNode updatedNode in nodeList)
{
XmlNode updatedNode = newXmldoc.SelectSingleNode("//Orders/OrderId[position()='" +i + "']");
string salesOrderId = updatedNode.SelectSingleNode("ID").InnerText;
updatedNode.SelectSingleNode("Title").InnerText ="Specified Customer";
XmlNode UpdateTitle = newXmldoc.CreateNode(XmlNodeType.Element, "MetaTitle", null);
UpdateTitle.InnerText = "Desired Customer";
updateNode.AppendChild(UpdateTitle);
i++;
}
newXmldoc.Save(Server.MapPath("~/XMLFiles/salesOrder.xml"));
}

Wednesday, March 21, 2012

How to create RSS in ektron CMS

Here i will show how to create a RSS for collection data in Ektron cms.In ektron cms we have an option ecmRssCollection method to get the data to rss feed object.There one more server control i:e RSSagrregator is also used to ge the rss feed data.I have collection control in my results page.When ever click on the Rss feed the query string value is passed to the rss page .The rss page shouldn't have HTML content.By default the aspx page has HTML content so we have to remove the content in this page.If we don't remove the html content in page we not get the rss data in Chrome browser.The 15 is the collection default ID in work area

if (Request.QueryString["rss"] == "collectionDatatest")
{
object rssFeedData = null;
Ektron.Cms.UI.CommonUI.ApplicationAPI AppCUI = new Ektron.Cms.UI.CommonUI.ApplicationAPI();
rssFeedData = AppCUI.ecmRssCollection(15)
Response.ContentType = "text/xml";
Response.Write(rssFeedData);
}

Tuesday, March 20, 2012

How to send a mail in ektron cms

In Ektron CMS we have a reference to send a mail i;e EkMailRef.This service has taken the server name from the web.config file.In web.config file the ek_key values are available to give the server name ,from and to user name.The below code will use to send a mail in ektron cms

CommonApi commonApi = new CommonApi();
EkMailService MailService = commonApi.EkMailRef;
MailService .MailFrom = "bhaskar7698@gmail.com;
MailService .MailTo = bhaskar7698@gmail.com;
MailService .MailSubject = "Test";
MailService .MailBodyText = "send mail in ektron cms;
MailService .SendMail();

Monday, March 19, 2012

How to get the id of checkbox in gridvew in jquery

Here a jquery on click method is used to get the id of checkbox in the gridview.In this when ever click on the submit button the grid view id is pass to jquery variable and find the which check box is checked
Script:
$(document).ready(function () {
$("#sub").click(function () {
var $checkedChB = $('#').find("input:checkbox:checked");
});
});

Thursday, March 15, 2012

How to change the array size at runtime in c#

Here i will show how to accept array size at run time and accepting elements in asp.net,Providing size of array at run time called"Dynamic array".This can be implemented in vb.net using "ReDim statement".
For the performance based static array provides better performance compare with custom array.The dynamic array should be used when array size changed at run time

c#:
submain();
byte[] a = null;
byte n = 0;
byte i = 0;
FileSystem.WriteLine("enter arrary size:");
n = ReadLine();
a = new byte[n];
FileSystem.WriteLine("Enter Elelments");
for (i = 0; i <= a.lenth - 1; i++) {
 a[i] = ReadLine;
}
VB:
submain()
Dim a() as byte
Dim n,i as byte
writeline("enter arrary size:")
n=ReadLine()
ReDim a(n-1)
WriteLine("Enter Elelments")
for i=0 to a.lenth-1
a(i)=ReadLine
Next

Wednesday, March 14, 2012

Excel Data into grid view in asp.net

Title:
How to import Excel data to grid view in asp.net using c#

Description:
Reporting is the key features of any application.Because the end user wants the see the data what they want.
Some time we might need to import the data from files(Excel) ,then insert into data base.So i would like to explain one example for importing

Example:
The recent recent post have given the process of exporting.how to export grid view data to excel,Export Grid view Data to Word Document in asp.net,Export Grid view data to PDF document in asp.net,Import XML data to Grid View.Here i will show how to Import the Excel data to Grid view.For this i have used OLEDB connection to connect the excel database.Then get the data of sheet1 in to Data Adapter and fill the data set.Finally this data is bind to Grid view Excel to grid view in asp.net process:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvImpOrder"  AllowPaging="True" Runat="server" AutoGenerateColumns="False">
<asp:Button ID="btnImportOrders" runat="server" Text="Import excel Data" 
onclick="btnImportOrders_Click" /></div>
</form>
</body>
</html>

Code behind:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class ImportExcelToGidview : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnImportOrders_Click(object sender, EventArgs e)
{
String Con = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=D:\\ImportGidview\OrderReport.xls;" +
"Extended Properties=Excel 8.0;";
OleDbConnection objCn = new OleDbConnection(con);
DataSet ds = new DataSet();
OleDbDataAdapter Oda = new OleDbDataAdapter("select * from[Sheet1$]", Con); 
Oda.Fill(ds);
GVImpOrder.DataSource = ds.Tables[0].DefaultView;
GVImpOrder.DataBind();
}
}

Tuesday, March 13, 2012

How to create a chart in excel in asp.net

Here i will show how to create a chart in excel sheet using csharp.TO create a chart in excel we have to use Excelchart objects.Then we will give the range for this chart in excel sheet dynamically.Here i have used data set records which is having the monthly reports.Here the reports are generated for year ,so we will get the 12 reports.
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(400, 230, 350, 200);
Excel.Chart chartPage = myChart.Chart;
tempcount = "y" +noofreports.tostring;
chartRange = xlWorkSheet.get_Range("x1", tempcount);
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Excel.XlChartType.xlLine;
//change font size of title
chartPage.ChartTitle.Characters.Font.Size = 12;
//remove majorticks
Excel.Axis x_axis = (Excel.Axis)chartPage.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary);
chartPage.ChartTitle.Characters.Text = "Chart in Excel sheet";
chartPage.Legend.Clear();
chartPage.HasTitle = true;

Sunday, March 11, 2012

how to create a custom page in sharepoint 2010

Here i will show how to create a custom aspx in share point.In this we get the root Share Point site, Then create a custom page with content and added to page collection .The page collection contains published pages in sharepoint website.Finally we will update the created custom page into collection using update command.
PublishingWeb PubWeb = PublishingWeb.GetPublishingWeb(SPContext.Current.Site.RootWeb);
string PageName = “Home.aspx”;
PageLayout[] layouts = PubWeb.GetAvailablePageLayouts();
PageLayout layout = layouts[0];
PublishingPageCollection  PCpages =PubWeb.GetPublishingPages();
PublishingPage PubPage = PCpages.Add(PageName, layout);
PubPage.ListItem[FieldId.PublishingPageContent] = “Homecontent”;
PubPage.ListItem.Update();
PubPage.Update();

Saturday, March 10, 2012

datalist control in asp.net

In previous articles i explained how to bind data to dropdownlist and Gridview,Export Gridview data to PDF document,dynamically add rows to Grid view in asp.net using c#. Here i will show how to display the images with zooming option in Data list.Data list doesn't provide built in structure for presenting data.So we(developers) provide required custom structure.The Grid view is not applicable for this above requirement .because grid view comes with Table structure,This can not be changed.We can use Repeater for this Requirement
Default.aspx:
<Header Template>
</HeaderTemplate><Header Style Horizontal Align="center" BackCoor="aqua" ForeColor="Blue"/>
<ItemTemplate>
<asp:Lable id="l1" runat="server" Text='<% #Eval("name")%>'>
</asp:Lable><br/>
<asp:Image src='<% #Eval("name")%>' Height="60" Width="60">
<br/>
<asp:Panel id="p1" runat="server" Height="60" Width="60" scrollBars="vertical">
<% #Eval("name")%>
</asp:Panel><br/>
<asp:CheckBox id="c1" runat="server" />
<br/>
<asp:Button  id="btn" runat="server" Text="Zoom" CommandArgument='<% #Eval("name")%>'/>
</ItemTemplate>
<ItemStyle BackColor="Blue" Bordrcolor="Yellow" Borderstyle="Dotted"/>
<FooterTemplate>
No of wonders=<% #Datalist1.Items.count%>
</FooterTemplate>


Codebehind:
if(Page.isPostBack==false)
{
Dabaselib.mycomponent obj=New databaselib.mycomponent();
Dataset ds=onj.Getinfo("useid="sa"; password=; Database="test","Select*from wonders");
Datalist1.Datasource=ds.Tables[0];
Datalist1.DataBind();
}
When use click zoom button postback will takes place.ItemCommand event of datalist will be excuted.Item Command event will proivde Command Argument value of selected button
//Zoom when we clik on image
protected void Datalist1-itemCommand(Object sender, DataListCommandEventArgs e) 
{
Response.Write("zoom.aspx?="+e.CommandArgument);
}
The zoom.aspx will show the image with zooming

Friday, March 9, 2012

how to send a mail with attachment in asp.net

In previous articles we have seen how to send a mail in asp.net,send HTML formated mail.In this post i will show how to send mail with attachment.Here the local file  which in root directory of the application has been used as attachment for mail.This scenario will be place when we send error log files to our mail.
Note:place code in Button click event which has to be used for send mail functionality
path_profile = AppDomain.CurrentDomain.BaseDirectory;
path_profile = path_profile + @"Log\Adminmailfile.txt";

string ServerName = ConfigurationManager.AppSettings["smtpservername"].ToString();
string FromAddress = ConfigurationManager.AppSettings["fromaddress"].ToString();
string adminmail = ConfigurationManager.AppSettings["AdminMail"].ToString();
string User = ConfigurationManager.AppSettings["user"].ToString();
string PWD = ConfigurationManager.AppSettings["PWD"].ToString();
DataSet dsmonthname = clsdb.getmonthname(cmonth);
//send message
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(ServerName);
mail.From = new MailAddress(FromAddress);
mail.To.Add(adminmail);
mail.Subject = "Alert" + System.DateTime.Now;
mail.Body = "Alert" + System.DateTime.Now;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(path_profile);
mail.Attachments.Add(attachment);
SmtpServer.Credentials = new System.Net.NetworkCredential(User, PWD);
SmtpServer.Send(mail);
Vb:
path_profile = AppDomain.CurrentDomain.BaseDirectory
path_profile = path_profile & "Log\Adminmailfile.txt"

Dim ServerName As String = ConfigurationManager.AppSettings("smtpservername").ToString()
Dim FromAddress As String = ConfigurationManager.AppSettings("fromaddress").ToString()
Dim adminmail As String = ConfigurationManager.AppSettings("AdminMail").ToString()
Dim User As String = ConfigurationManager.AppSettings("user").ToString()
Dim PWD As String = ConfigurationManager.AppSettings("PWD").ToString()
Dim dsmonthname As DataSet = clsdb.getmonthname(cmonth)
'send message
Dim mail As New MailMessage()
Dim SmtpServer As New SmtpClient(ServerName)
mail.From = New MailAddress(FromAddress)
mail.[To].Add(adminmail)
mail.Subject = "Alert" & System.DateTime.Now
mail.Body = "Alert" & System.DateTime.Now
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment(path_profile)
mail.Attachments.Add(attachment)
SmtpServer.Credentials = New System.Net.NetworkCredential(User, PWD)
SmtpServer.Send(mail)

Thursday, March 8, 2012

How to get the cookie value in asp.net

Here i will show how to set and get the cookie value.Cookies are used to store the small size of data in browser.The below example gives , how perform manipulate functions on cookies .In my application i have three page and each page having two image buttons.When ever click on the image button ,it redirect to next page.In this process we will also pass the value of cookie.
c#:
protected void imgpinksubmit_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
SetCookie("p");
Response.Redirect("test.aspx");
}
protected void Imgbluesubmit_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
SetCookie("b");
Response.Redirect("test1.aspx");
}
private void SetCookie(string c)
{
if (Request.Cookies("Colors") == null) {
Request.Cookies.Add(new HttpCookie("Colors", ""));
}
int pageIndex = 1;
string colorCode = Request.Cookies("Colors").Value;
if (!string.IsNullOrEmpty(colorCode)) {
if (colorCode.Contains("1," + c)) {
}
else
{
string[] colors = colorCode.Split('|');
if (colors.Length >= pageIndex) {
colors[pageIndex - 1] = pageIndex + "," + c;
string updatedColorcode = string.Empty;
for (int i = 0; i <= colors.Length - 1; i++) {
updatedColorcode += colors[i] + "|";
}
Response.Cookies("Colors").Value = updatedColorcode.TrimEnd('|');
}
}
}
else
{
Response.Cookies("Colors").Value = "1," + c;
}
}
vb#:
Protected Sub imgpinksubmit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgpinksubmit.Click
SetCookie("p")
Response.Redirect("test.aspx")
End Sub

Protected Sub Imgbluesubmit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Imgbluesubmit.Click
SetCookie("b")
Response.Redirect("test1.aspx")
End Sub

Private Sub SetCookie(ByVal c As String)
If Request.Cookies("Colors") Is Nothing Then
Request.Cookies.Add(New HttpCookie("Colors", ""))
End If
Dim pageIndex As Integer = 1
Dim colorCode As String = Request.Cookies("Colors").Value
If Not String.IsNullOrEmpty(colorCode) Then
If colorCode.Contains("1," & c) Then
Else
Dim colors As String() = colorCode.Split("|"c)
If colors.Length >= pageIndex Then
colors(pageIndex - 1) = pageIndex & "," & c
Dim updatedColorcode As String = String.Empty
For i As Integer = 0 To colors.Length - 1
updatedColorcode += colors(i) & "|"
Next
Response.Cookies("Colors").Value = updatedColorcode.TrimEnd("|"c)
End If
End If
Else
Response.Cookies("Colors").Value = "1," & c
End If
End Sub  

Tuesday, March 6, 2012

how to install IIS webserver in asp.net

The asp.net is server side web specification .In the asp.net we can work with IIS web server.The web server maintains collection of proxy machines ,very flexibility depending on the request ,the we service gives the response,The total application control by web server.Web server having the virtual memory

start-->settings-->control panel-->add remove program-->windows components-->click on the this available one component IIS-->click on next
Web server features are not getting with operating system,manually we have to install IIS Webserver.

Installing IIS web server:

To install the web server go to add remove programs by click on the start menu-->settings-->control panel->add remove program--> add windows components-->getting list of components from the operating system.

From the list of components select Internet Information Service check box .Click on the next button ,web server is installed

Monday, March 5, 2012

how to upload multiple files in asp.net

Here i will show how to upload multiple file using File upload control in asp.net.For this i have taken one HttpFileCollection to upload the multiple files.

CodeBehind:
protected void btnUpload_Click(object sender, EventArgs e)
{ 
if (FileUpload.HasFile)
{ 
// Get the HttpFileCollection
HttpFileCollection uploadeFiles = Request.Files;
for (int i = 0; i < uploaded.Count; i++) { HttpPostedFile Hpostfiles = uploadedFiles[i]; if (Hpostfiles.ContentLength > 0)
{
Hpostfiles.SaveAs(Server.MapPath("~/Upload/Test/") + Path.GetFileName(Hpostfiles.FileName));
}
} 
}
}

How to create a Infopath form in sharepoint 2010

Here i will describe how to create an InfoPath form in share point 2010.Go to InfoPath 2010 Designer and click on the file-->New-->select blank form . Whenever we click on the blank form we will get an option to design the Form


Then i have insert a table into the form using following option.Go to Insert tab-->we can see the table formates at that.
Then add desired controls based on requirement.Here i have added to add controls to add the data of sale persons.Go to home-->Here we can see the option on right top is Controls.
After all this process has done ,we can publish our InfoPath form to  share point Library.

Saturday, March 3, 2012

how to upload a file in wcf

Here i will show how to upload a file in WCF serve rice.The streaming concept is used to implement a wcf service to upload a file.I have created a wcf project i:e UploadFile.svc then Open the IUploadFile.cs and add following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
[ServiceContract]
public interface IUploadFile
{
    [OperationContract]
    string FileUpload(Stream inputStream);
    [OperationContract]
    Stream FileDownload(string fId);
    [OperationContract]
    string[] GetFiles();
}
CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Web;

public class UploadFile : IUploadFile
{
    private const string PATH = @"C:\wcf\download";

    private string GetDirectoryinfoPath()
    {
        return PATH;
    }
    public string FileUpload(System.IO.Stream inputStream)
    {
        string fID = string.Format(@"{0}\{1}.txt", GetDirectoryinfoPath(), Guid.NewGuid().ToString());
        StreamReader sreader = new StreamReader(inputStream);
        string filecontents = sreader.ReadToEnd();
        File.WriteAllText(fID, filecontents);
        return fID;
    }
   public string[] GetFiles()
    {
        return new DirectoryInfo(GetDirectoryinfoPath()).GetFiles().Select(x => x.FullName).ToArray();
    }
 
}

Configuration File:
Now we have to give some configuration settings for wcf service.
<system.servicemodel>
<services>
<service behaviorconfiguration="streamServiceBehaviour" name="UploadFile">
<endpoint address="" binding="basicHttpBinding" bindingconfiguration="streamBindingConfig" contract="IUploadFile">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange">
</service>
</services>
<behaviors>
<servicebehaviors>
<behavior name="streamServiceBehaviour">
<servicedebug includeexceptiondetailinfaults="true">
<servicemetadata httpgetenabled="true">
</behavior>
</servicebehaviors>
</behaviors>
<bindings>
<basichttpbinding>
<binding name="streamBindingConfig" transfermode="Streamed">
</binding>
</basichttpbinding>
</bindings>
</system.servicemodel>


Then i have add a new with file upload control.Then add the following code to code behind.
using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class UploadExample : System.Web.UI.Page
{
    StreamService.FileStreamClient wclient = new StreamService.FileStreamClient();
    string fileId = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
      fId=wclient.FileUpload(new MemoryStream(FileUpload1.FileBytes));
    }
  
}

Friday, March 2, 2012

How to Get the MetaData of ContentBlock in Ektro CMS

Here i will show how to get the meta data of content in ektron CMS.We have some API features to get the meta data of content block.In this One is Content API and other one is meta data API.The another way i:e Taxonomy is used to get the content block details.But it to difficult comparing with existing API.Here the content id is getting from Page host then pass to content Id variable.Then get the meta data of content using following code

codebehind:

Ektron.Cms.Controls.ContentBlock cb = new Ektron.Cms.Controls.ContentBlock();
cb.DefaultContentID = contentid;
Ektron.Cms.API.Content.Content CAPi = new Ektron.Cms.API.Content.Content();
Ektron.Cms.ContentData CData = new Ektron.Cms.ContentData();
CData = CAPi.GetContent(contentid, Ektron.Cms.
ContentAPI.ContentResultType.Published);
Label lbf = new Label();
lbf.Text = "

"+CData.Title.ToString()+"

"; string image=CData.Image.ToString();
// using meta data API
Ektron.Cms.API.Metadata mapi = new Ektron.Cms.API.Metadata();
Ektron.Cms.CustomAttributeList cList = new Ektron.Cms.CustomAttributeList();
cList = mapi.GetContentMetadataList(contentid); 
//Content ID
Response.Write(cList.AttributeList.Length.ToString());
Response.Write(cList.GetItemByName("Image"));

Bel