ĐÀO TẠO DOANH NGHIỆP : SỞ KHOA HỌC CÔNG NGHỆ TỈNH ĐỒNG NAI

ENTERPRISE TRAINING: DONG NAI DEPARTMENT OF SCIENCE AND TECHNOLOGY.

HÌNH ẢNH TẬP HUẤN LỚP SHAREPOINT WORKFLOW VÀ KIẾN TRÚC SHAREPOINT

PHOTOS OF SHAREPOINT WORKFLOW AND ARCHITECTURE CLASS.

HÌNH ẢNH TẬP HUẤN LỚP SHAREPOINT WORKFLOW VÀ KIẾN TRÚC SHAREPOINT

PHOTOS OF SHAREPOINT WORKFLOW AND ARCHITECTURE CLASS.

Thursday, October 31, 2013

Sharepoint interview questions from VietNam's company

Part 1
1.     Different spsite and spweb ?
a.     SPSite is a site collection
b.    SPWeb is an SharePoint Website under site collection in Sharepoint (or "Site" from the UI), this includes subsites
2.     What is CAML?
CAML - also called as Collaborative Application Markup Language is the custom XML language in SharePoint.
3.     What is Content types and site column Sharepoint?
a.     Content types core organizational, contain site columns to reuse in sharepoint list content type
b.    Site column is created within content type or added to list
4.     What is ONET.xml?
a.     Onet.xml file specifies all the components contained in a site. It is considered as the core of a site definition.
b.    It is present at following location: %SharePoint Root% \TEMPLATE\SiteTemplates\XML\Onet.xml
5.     Differentiate between Library and List?
a.     Library is used to store the document.
b.    Lists is used to store the items, List can be used to attach a document.
6.     Web Part life cycle in SharePoint 2010?
a.     OnInit, OnLoad, CreateChildControls, EnsureChildControls, SaveViewState, OnPreRender, Page.PreRenderComplete, Render, RenderContents, OnUnload.
7.     What is the difference between the farm and sandbox?
a.     Farm solutions
                                          i.    Farm solutions are hosted in the IIS worker process (W3WP.exe).
                                         ii.    If you run any code in farm solution the whole farm will got affected.
                                        iii.    If you deploy any feature or retract any feature the whole application pool got recycled.
                                        iv.    Since they are scoped as farm level, they have full trust access to all the resources.
                                         v.    When the Sandboxed Solution property is set to False, selecting Build\Deploy will deploy the solution to the Farm Solution Gallery
b.    Sandbox solutions
                                          i.    Sandboxed solutions are hosted in the SharePoint user code solution worker process (SPUCWorkerProcess.exe).
                                         ii.    The process runs under a CAS policy that restricts programmatic access to any resource outside the sandbox.
                                        iii.    Never restart the IIS application pool.
                                        iv.    If you run any code it will affect only the site collection of the solution.
                                         v.    Helpful if you have shared hosting.
                                        vi.    When the Sandboxed Solution property is set to True, selecting Build\Deploy Solution deploys the solution to the site collection Solution Gallery.
8.     What is a SharePoint site definition??
SharePoint sites consist of numerous Web pages, just like an ASP.NET 2.0 application.
When a site is created, these pages are created as instances in the content database.
The instances refer to the actual file on the file system.
9.     What are the Disadvantages of Using LINQ in your Code?
a.     LINQ translates the LINQ queries into Collaborative Application Markup Language (CAML) queries thus adding an extra step for retrieving the items.
10.  What are new feature in sharepoint 2010?
a.     Sandboxed Solutions
b.    New User Interface including Ribbon
c.     Built-in SilverLight Support
d.    Access Services
e.     Managed Metadata
f.     Visio Services
g.    PerformancePoint Services
h.     Language Integrated Query (LINQ) for SharePoint
i.      Multi-Tenant Hosting
j.     
11.  What are Web Applications in SharePoint?
a.     An IIS Web site created and used by SharePoint 2010
12.  What is a site collection?
a.     A site collection contains a top-level website and can contain one or more sub-sites web sites that have the same owner and share administration settings.
13.  What are content databases?
a.     A content database can hold all the content for one or more site collections
14.  What is Managed Metadata?
a.     Managed metadata is a hierarchical collection of centrally managed terms that you can define, and then use as attributes for items.
15.  What does AllowUnsafeUpdates do?

a.     If your code modifies Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. You can do by setting the AllowUnsafeUpdates property.
Part 2
1.       What is viewstate and how to use?
a.    It is used to store data the page value at the time of post back
b.    Example: when you input value to TextBox then click button=> after page postback data is stored to the viewstate
c.    Declare viewstate: ViewState["NameOfUser"] = FieldInput.Text;
d.    Use ViewState: FieldLabel.Text=ViewState["NameOfUser"].ToString();
2.    Event Life cycle asp.net ?
a.    Page_Init
b.    LoadViewState
c.    LoadPostData
d.    Page_Load
e.    RaisePostDataChangedEvent
f.     RaisePostBackEvent
g.    Page_Prerender
h.    SaveViewState
i.      Page_Render
j.      Page_Unload
3.     SPWebapplication vs SPWebService ?
Adding vs Added?
4.     Using Linq List<Order> to query data with length of string > 50
5.     Unit VS Int
6.     In EF 5.0 disadvantage of inclucde clause
7.     Describe the case out of box listviewwebpart can not use, and you use custom webpart
8.    Select class Jquery and count
a.    Var numberItem= $(‘.item’).length;
9.    Caml Query: get employee with FullName is Mary
a.    spQuery.Query=”<Where><Eq><FieldRef Name=’FullName’/><Value type=’Text’> Mary</Value><Eq></Where>”
10.  Entity framework: purpose of include clause
I often use theObjectQuery.Include method to eagerly load associated entities, in order to avoid database roundtrips when I access them:



var query =
    from ord in db.Orders.Include("OrderDetails")
    where ord.Date >= DateTime.Today
    select ord;

11. Analyst performance in implement entity framework?
Avoid fetching all the fields if not required
Retrieve only required number of records (rows)
Avoid using Contains
Avoid using Views
Use Compiled Query
Must examine Queries before being sent to the Database
Efficiently Loading Related Data
Select appropriate Loading type while defining model
12. What is metadata service in sharepoint 2010? Purpose of metadata service?
a.    Managed Metadata is a hierarchical collection of terms that can be associated with items in SharePoint 2010. We can use Central Administration website to manage these terms.
b.    Purpose: Term Sets can be shared across a site collection or globally, S earching using Metadata gives more relevant result
13. C# elevate spweb from a url?
SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                             //Code here
                     }
                 }
                 });
14. What isThe UNION operator used to?
a.    The UNION operator is used to combine the result-set of two or more SELECT statements.
b.    Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.
15. Get amount order from three tables (Customers, Orders, OrderDetails) which customerid= 111?
select COUNT(Orders.OrderID) as amountoforder,Customers.CustomerID
from Customers inner join Orders on Customers.CustomerID=Orders.CustomerID where Customers.CustomerID=111
group by Customers.CustomerID
16. Index in SQL server
a.    INDEX statement is used to create indexes in tables.
b.    An index can be created in a table to find data more quickly and efficiently.
c.    The users cannot see the indexes, they are just used to speed up searches/queries.
d.    Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
17. Content Type ID Structure?
The content type ID of the basic content type Item is 0x01 (System: 0x, Item: 0x01). This denotes that the Item content type is a direct child of System. The content type ID of the Document content type is 0x0101, and the Folder content type has a content type ID of 0x0120.
18. WCF advantage nettcpbinding vs basic httpbinding
Binding
Security
Default Configurable
Transport Protocol
Encoding
Default Other
Host
basicHttpBinding
None,
Transport, Message, Mixed
HTTP
Text/XML, MTOM
IIS, WAS
netTcpBinding
Transport, Message, Mixed
TCP
Binary
WAS

Tuesday, October 15, 2013

SharePoint 2010: “Your client does not support opening this list with windows explorer”

SharePoint 2010: “Your client does not support opening this list with windows explorer”

Scenario
We want to open the document library in explorer view
But somehow it’s popping up with the message “Your client does not support opening this list with windows explorer”?
Solution
Use 32 bits IE, because it’s the featured for this browser
If your using windows server 2008, enabled “Desktop Experience” feature

Go back to your document library >> Library tab >> click to Open With Explorer

Copy Folder and file in folder to Explorer

Go back your document library then click f5

Thanks.

Monday, October 14, 2013

Custom properties for visual webpart 2010

Custom properties for visual webpart
You should read 3 article first
http://mstechsharing.blogspot.com/2012/03/lesson-04-webpart-property-and-default.html
http://mstechsharing.blogspot.com/2012/03/lesson-05-more-attribute-and-custom.html
http://mstechsharing.blogspot.com/2012/03/lesson-06-validation-in-webpart-and.html

Create new Visual webpart project


Add new class for toolpart class

Open CustomPropertiesForVisualWebpart.cs and Replace this code
using System.ComponentModel;
using System.Web.UI;
using Microsoft.SharePoint.WebPartPages;

namespace CustomPropertiesForVisualWebpart.CustomPropertiesForVisualWebpart
{
    [ToolboxItemAttribute(false)]
    public class CustomPropertiesForVisualWebpart : WebPart
    {
     
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/CustomPropertiesForVisualWebpart/CustomPropertiesForVisualWebpart/CustomPropertiesForVisualWebpartUserControl.ascx";

        protected override void CreateChildControls()
        {
            CustomPropertiesForVisualWebpartUserControl control = (CustomPropertiesForVisualWebpartUserControl)Page.LoadControl(_ascxPath);
            //Assign value to Attribute of webpart user control
            control.Attributes.Add("DisplayCar", DisplayCar);
            Controls.Add(control);
        }

        #region properties
        public string _value;// public static string _value; (Note: remove static)
        public string Value
        {
            get { return _value; }
            set { _value = value; }
        }

        string displayCar = "1";
        public string DisplayCar
        {
            get { return displayCar; }
            set { displayCar = value; }
        }
        #endregion
        /// <summary>
        /// return all toolpat
        /// </summary>
        /// <returns>return toolpart</returns>
        public override ToolPart[] GetToolParts()
        {
            ToolPart[] allToolParts = new ToolPart[3];
            WebPartToolPart standardToolParts = new WebPartToolPart();
            CustomPropertyToolPart customToolParts = new CustomPropertyToolPart();
            allToolParts[0] = standardToolParts;
            allToolParts[1] = customToolParts;
            allToolParts[2] = new CustomToolPart();
            return allToolParts;
        }
    }
}
Open CustomToolPart and replcae this code
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using System.Data;


namespace CustomPropertiesForVisualWebpart.CustomPropertiesForVisualWebpart
{
    public class CustomToolPart : Microsoft.SharePoint.WebPartPages.ToolPart
    {
        #region variable
        /// <summary>
        /// declare variable
        /// </summary>
        Label lblError;
        DropDownList ddlDisplayCar;
        TextBox txtValue;
        #endregion
        /// <summary>
        /// Create Control
        /// </summary>
        protected override void CreateChildControls()
        {
            try
            {
                lblError = new Label();
                Label lblDisplayCar = new Label();
                lblDisplayCar.Text = "Choose display car: <br />";
                ddlDisplayCar = new DropDownList();
                ddlDisplayCar.ID = "ddlDisplayCar";
                ddlDisplayCar.Items.Add(new ListItem("All Cars", "1"));
                ddlDisplayCar.Items.Add(new ListItem("All Cars of Current User", "2"));
                txtValue = new TextBox();

                this.Controls.Add(lblError);
                this.Controls.Add(lblDisplayCar);
                this.Controls.Add(ddlDisplayCar);
                this.Controls.Add(txtValue);
                DisplayDataFromWebpartToToolPart();
            }
            catch (System.Exception ex)
            {
                lblError.Text = ex.Message;
                //You can write log here
            }
        }
        /// <summary>
        /// Display Data From Webpart To ToolPart
        /// </summary>
        private void DisplayDataFromWebpartToToolPart()
        {
            //Display data from webpart to toolpart
            CustomPropertiesForVisualWebpart customPropertiesVisualWP = (CustomPropertiesForVisualWebpart)this.ParentToolPane.SelectedWebPart;
            // DisplayCar
            ListItem currentDisplayCar = ddlDisplayCar.Items.FindByValue(customPropertiesVisualWP.DisplayCar);
            if (null != currentDisplayCar)
            {
                ddlDisplayCar.SelectedValue = currentDisplayCar.Value;
            }

            txtValue.Text = customPropertiesVisualWP.Value;
        }
        /// <summary>
        /// Apply changes when we click button Apply and Ok in toolpart panel
        /// </summary>
        public override void ApplyChanges()
        {
            CustomPropertiesForVisualWebpart customPropertiesVisualWP = (CustomPropertiesForVisualWebpart)this.ParentToolPane.SelectedWebPart;
            customPropertiesVisualWP.DisplayCar = ddlDisplayCar.SelectedValue;
            customPropertiesVisualWP.Value = txtValue.Text;
        }
    }
}
Open CustomPropertiesForVisualWebpartUserControl.ascx and Add 2 Label then open CustomPropertiesForVisualWebpartUserControl.ascx.cs and replcae this code
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
namespace CustomPropertiesForVisualWebpart.CustomPropertiesForVisualWebpart
{
    public partial class CustomPropertiesForVisualWebpartUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblCarWay1.Text = Convert.ToString(this.Attributes["DisplayCar"]);
            lblCarWay2.Text = CustomPropertiesForVisualWebpart._value;
        }
    }
}
Build and Deploy then add webpart => edit properties webpart


Thursday, October 10, 2013

Attach file to sharepoint list item by sandbox


Sharepoint 2013 Online: Attach file to sharepoint list item by sandbox

Download Project MstechsharingSPO
Hello everybody! Today i post this article with the my pleasure. i found the limitation of sandbox in upload and attach file to list item. It is System.IO namespace, the sandbox code can not read the Path.GetFileName (it inherit from System.IO), so we get filename's value is null.

I thought the solution: attach file using upload file of sharepoint. Moreover, we attach file when we add new item, so we must have the existing item. The final, i create the List "MstechsharingTemp" to store attachment file of each users login to system. When i click attach file, file will be saved into list "MstechsharingTemp" with existing item then when click Post (Save) button, i will store item into my "Mstechsharing" and copy attachment file from "MstechsharingTemp"  list to my list "Mstechsharing".
Here is step by step i did:
Login to sharepoint online site (my case is SPO). Create new list MstechsharingTemp by go to Settings >> Add an app >> choose Custom list template

Continue create the next custom list "Mstechsharing"

Now we create Visual webpart in sandbox solution. we don't have available visual webpart for sandbox, so we must download "SpPowerTools_x86_enu_DeployVSWebpartAsSandbox". Setup it then wait some minutes we will see it by Open visual studio >> New project >> Empty Sharepoint Project with name is MstechsharingSPO

Deploy as Sandbox solution

Right click to project Mstechsharing >> New Item >> choose Visual Web Part (Sandboxed) with name is Mstechsharing

User interface look like

Open MstechsharingSPO.ascx

code here
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Mstechsharing.ascx.cs"
    Inherits="MstechsharingSPO.Mstechsharing.Mstechsharing" %>
<script type="text/javascript">
    function callback() {
        alert('document uploaded');
    }
    function openPopup() {
        var elem = document.getElementById('<%= hdnURL.ClientID %>');
        var options = {
            url: elem.value,
            title: 'Modal Dialog',
            allowMaximize: false,
            showClose: true,
            width: 500,
            height: 200,
            dialogReturnValueCallback: callback
        }
        SP.UI.ModalDialog.showModalDialog(options);
        return false;
    }
</script>
Title:
<asp:TextBox ID="txtObject" runat="server" Width="300px"></asp:TextBox>
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="Attach file" id="btnAttachFile" runat="server" onclick="return SP.SOD.executeFunc('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', function () { openPopup(); });"
    disabled="disabled" style="width: 128px" />
<input type="hidden" runat="server" id="hdnURL" />
<asp:Button ID="btnSave" runat="server" Text=" Save into Mstechsharing "
    Width="170px" onclick="btnSave_Click" />
<asp:HiddenField ID="hdnItemID" runat="server" />


Open MstechsharingSPO.ascx.cs and Copy code into Page_Load.
Note: Change you ListId is very important

Code here
protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                int itemID = DeleteExistingAttachments();

                if (itemID == 0)
                {
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            SPList SPLData = web.Lists["MstechsharingTemp"];
                            SPListItem item = SPLData.Items.Add();
                            item.Update();
                            hdnItemID.Value = item.ID.ToString();
                        }
                    }
                }
                else
                {
                    hdnItemID.Value = itemID.ToString();
                }
            }
            string urlFormat = "/_layouts/AttachFile.aspx?ListId={0}&ItemID={1}";
            string url = string.Format(urlFormat, "{E4D0A1CC-CEE0-4FF1-98DE-19B5D2AF943F}", hdnItemID.Value);
            hdnURL.Value = url;
            btnAttachFile.Disabled = false;
        }

Continue copy 2 method DeleteExistingAttachments() and CopyAttachments below Page_Load


code here
private int DeleteExistingAttachments()
        {
            int itemId = 0;
            // Follow the steps to delete list item attachment from your sharepoint list.
            // Create new instance of site with your current application
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                // Create new web instance and open web for current application
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    // Create new list object and get your list
                    SPList SPLData = web.Lists["MstechsharingTemp"];
                    // Create new query object to hold query which fetches list item of the list
                    SPQuery spMyQuery = new SPQuery();
                    // Assign query with value to it in ID field of the list item
                    spMyQuery.Query = "<Where><Eq><FieldRef Name='Author'/><Value Type='Integer'><UserID Type='Integer' /></Value></Eq></Where>";
                    SPListItemCollection collection = SPLData.GetItems(spMyQuery);
                    if (collection.Count > 0)
                    {
                        SPListItem listItem = collection[0];
                        itemId = Convert.ToInt32(listItem["ID"]);
                        if (listItem.Attachments.Count > 0)
                        {
                            foreach (string fileName in listItem.Attachments)
                            {
                                listItem.Attachments.Delete(fileName);
                                listItem.Update();
                            }
                        }
                    }
                    web.AllowUnsafeUpdates = false;
                }

            }
            return itemId;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sourceItem"></param>
        /// <param name="targetItem"></param>
        private void CopyAttachments(SPListItem sourceItem, SPListItem targetItem)
        {
            try
            {
                //get the folder with the attachments for the source item
                SPFolder sourceItemAttachmentsFolder =
                    sourceItem.Web.Folders["Lists"].SubFolders[sourceItem.ParentList.Title].SubFolders["Attachments"].SubFolders[sourceItem.ID.ToString()];
                //Loop over the attachments, and add them to the target item
                foreach (SPFile file in sourceItemAttachmentsFolder.Files)
                {
                    byte[] binFile = file.OpenBinary();
                    targetItem.Attachments.AddNow(file.Name, binFile);
                }
            }
            catch { }
            finally
            {
                sourceItem.Web.Dispose();
            }
        }

Double click to button Save and paste this code

Code here
 protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        SPList spListTopics = spWeb.Lists["Mstechsharing"];
                        SPListItemCollection spListItemCollectionTopics = spListTopics.Items;
                        SPListItem item = spListItemCollectionTopics.Add();
                        item["Title"] = txtObject.Text;
                        item.Update();
                        SPList spListTemp = spWeb.Lists["MstechsharingTemp"];
                        SPListItem spListItemTemp = spListTemp.GetItemById(Convert.ToInt32(hdnItemID.Value));
                        SPListItem spListItemTopics = spListTopics.GetItemById(item.ID);
                        CopyAttachments(spListItemTemp, spListItemTopics);
                        DeleteExistingAttachments();
                       // Page.Response.Redirect(SPContext.Current.Web.Url);
                    }
                }
            }
            catch (Exception ex)
            {
                Page.Response.Write(ex.Message);
            }
        }
All code
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace MstechsharingSPO.Mstechsharing
{
    [ToolboxItem(false)]
    public partial class Mstechsharing : System.Web.UI.WebControls.WebParts.WebPart
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                int itemID = DeleteExistingAttachments();

                if (itemID == 0)
                {
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            SPList SPLData = web.Lists["MstechsharingTemp"];
                            SPListItem item = SPLData.Items.Add();
                            item.Update();
                            hdnItemID.Value = item.ID.ToString();
                        }
                    }
                }
                else
                {
                    hdnItemID.Value = itemID.ToString();
                }
            }
            string urlFormat = "/_layouts/AttachFile.aspx?ListId={0}&ItemID={1}";
            string url = string.Format(urlFormat, "{E4D0A1CC-CEE0-4FF1-98DE-19B5D2AF943F}", hdnItemID.Value);
            hdnURL.Value = url;
            btnAttachFile.Disabled = false;
        }

        /// <summary>
        ///
        /// </summary>
        private int DeleteExistingAttachments()
        {
            int itemId = 0;
            // Follow the steps to delete list item attachment from your sharepoint list.
            // Create new instance of site with your current application
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                // Create new web instance and open web for current application
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    // Create new list object and get your list
                    SPList SPLData = web.Lists["MstechsharingTemp"];
                    // Create new query object to hold query which fetches list item of the list
                    SPQuery spMyQuery = new SPQuery();
                    // Assign query with value to it in ID field of the list item
                    spMyQuery.Query = "<Where><Eq><FieldRef Name='Author'/><Value Type='Integer'><UserID Type='Integer' /></Value></Eq></Where>";
                    SPListItemCollection collection = SPLData.GetItems(spMyQuery);
                    if (collection.Count > 0)
                    {
                        SPListItem listItem = collection[0];
                        itemId = Convert.ToInt32(listItem["ID"]);
                        if (listItem.Attachments.Count > 0)
                        {
                            foreach (string fileName in listItem.Attachments)
                            {
                                listItem.Attachments.Delete(fileName);
                                listItem.Update();
                            }
                        }
                    }
                    web.AllowUnsafeUpdates = false;
                }

            }
            return itemId;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sourceItem"></param>
        /// <param name="targetItem"></param>
        private void CopyAttachments(SPListItem sourceItem, SPListItem targetItem)
        {
            try
            {
                //get the folder with the attachments for the source item
                SPFolder sourceItemAttachmentsFolder =
                    sourceItem.Web.Folders["Lists"].SubFolders[sourceItem.ParentList.Title].SubFolders["Attachments"].SubFolders[sourceItem.ID.ToString()];
                //Loop over the attachments, and add them to the target item
                foreach (SPFile file in sourceItemAttachmentsFolder.Files)
                {
                    byte[] binFile = file.OpenBinary();
                    targetItem.Attachments.AddNow(file.Name, binFile);
                }
            }
            catch { }
            finally
            {
                sourceItem.Web.Dispose();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        SPList spListTopics = spWeb.Lists["Mstechsharing"];
                        SPListItemCollection spListItemCollectionTopics = spListTopics.Items;
                        SPListItem item = spListItemCollectionTopics.Add();
                        item["Title"] = txtObject.Text;
                        item.Update();
                        SPList spListTemp = spWeb.Lists["MstechsharingTemp"];
                        SPListItem spListItemTemp = spListTemp.GetItemById(Convert.ToInt32(hdnItemID.Value));
                        SPListItem spListItemTopics = spListTopics.GetItemById(item.ID);
                        CopyAttachments(spListItemTemp, spListItemTopics);
                        DeleteExistingAttachments();
                        Page.Response.Redirect(SPContext.Current.Web.Url);
                    }
                }
            }
            catch (Exception ex)
            {
                Page.Response.Write(ex.Message);
            }
        }
    }
}
Now we build and package project then Open your site and go to Settings >> Site setting >> at Web Designer Galleries category click to Solutions >> Upload and active wsp file

Open MstechsharingTemp we don't see any item

Add webpart  "Mstechsharing Title"to page

Go back MstechsharingTemp we see an item was created with current user in page_load
Note: we check user is existing or not, if not exist we create new, else we delete all attachment file into existing item of current user login. So, make sure we f5 the item will not create

Now we upload file

Uploaded successful.

Go back to MstechsharingTemp we see file was attached to list item

Continue add new item and click button Save

Go back Mstechsharing list we see item and attachment file is created

Login to another user, we will see item was created in MstechsharingTemp list

So, you can create item and attach file similar at above steps.
Thanks.